Terminal exit without performing action - applescript

I've made a script which have a block of code launching Terminal to retrieve picture from a server, using FTP.
When I run the script under the script editor, everything is OK: the script launch the Terminal, open the FTP session, set the destination path, get the files, delete them from the server, close connexion, wait the end of Terminal activty and then quit.
But when I run my Script as application, in about 90% of cases, the app launch Terminal and then Terminal quit immediatly. When the Terminal seems to "get" correctly the FTP commands, connexion is done, getting file and so on. Perfectly. But this happens only in a few cases.
Here the last code I have for this part:
tell application "Terminal"
activate
-- Wait for "no more activity"
set frontWindow to window 1
repeat until busy of frontWindow is false
delay 1
end repeat
-- Perform FTP actins
set shell to do script "ftp -i ftp://user_ftp:pass_ftp#host_ftp/" in window 1
do script "lcd ~/Desktop/tmp_instagram/" in shell
do script "mget *.jpg" in shell
do script "mdel *.jpg" in shell
do script "bye" in shell
-- Wait for no more activity
set frontWindow to window 1
repeat until busy of frontWindow is false
delay 1
end repeat
end tell
tell application "Terminal" to quit saving no -- Saving no to avoid conf alert
For avoiding you to loose your time, here are some of the tests I've made, without any success:
Setting the whole FTP command in one line so.
Put a delay 5 after the ativate, rather than the repeat on busy
Put a delay after the ftp command
In fact, the Terminal seems to close before receiving the FTP command (opened and closed immediatly).

Thanks to Mark Setchell comment I tried without using the "shell" command and in fact it seems to be the key. Here is a piece of code which run correctly:
tell application "Terminal"
activate
set w to window frontmost
do script "ftp -i ftp://xxxxx:yy#dddddd/" in w
do script "lcd ~/Desktop/tmp_aarecno_instagram/" in w
do script "mget *.jpg" in w
do script "mdel *.jpg" in w
do script "bye" in w
set frontWindow to window 1
repeat until busy of frontWindow is false
delay 1
end repeat
end tell

Related

Bring Chrome started from script to front

I am wondering how I can launch a fresh new Chrome instance (see my script below) that will be brought to the front. Currently the shell script opens the new Chrome instance in the background, which is less than optimal. Executing the shell script from Applescript does nothing to remedy this.
The interesting thing is that if I open Chrome using a shell command directly from AppleScript it seems to open in the foreground:
set q to "'/Applications/Google Chrome.app/Contents/MacOS/Google Chrome' --user-data-dir=/tmp/1234"
do shell script q
Applescript
do shell script "~/bin/chrome-fresh"
Shell script
#!/bin/sh
# This is quite useful for front-enders, as it will launch a fresh
# Chrome instance with no loaded plugins or extensions that messes
# with your performance profiling or network debugging
#
# Install:
# install -m 555 ~/Downloads/chrome-fresh /usr/local/bin/
CHROME="/Applications/Google Chrome.app/Contents/MacOS/Google Chrome"
ARGS="$#"
# make a fresh user directory
TMP_USERDIR=$(mktemp -d);
# avoid the dialog on the first startup
touch "$TMP_USERDIR/First Run";
# start chrome using a fresh user directory
"$CHROME" --user-data-dir="$TMP_USERDIR" "$ARGS"
Run the command in background (put the & at the end of the command).
Use $! to get the process ID of the last command
# start chrome using a fresh user directory
"$CHROME" --activate-on-launch --user-data-dir="$TMP_USERDIR" "$ARGS" &
chromePid=$!
sleep 2
# bring Chrome
osascript -e 'tell application "System Events"' -e "tell (first process whose its unix id is \"$chromePid\" ) to set frontmost to true" -e 'end tell'
In the script bellow, I used a mix of Applescript and Shell commands. I am not Shell expert, so may be there are most efficient way to do it. At least, this script is working :
1) it takes all process containing specific name (i.e. = Chrome)
2) it goes through all found processes, and for each, get the time since it starts using "ps" shell command.
3) it compares that time with previous times found and if lower then it keeps the process information. The lowest time value is linked to the last starting instance of the process.
4) the process with the shortest time since it starts is the last one : it sets the frontmost property to true to make it foreground.
tell application "System Events"
set lastTime to 3600 -- max possible value of start time
set lastPID to -1 -- impossible : used to check if process has been found !
set Prlist to every process whose name contains "Chrome"
repeat with aProc in Prlist
set PStext to do shell script "PS -o etime -p " & unix id of aProc -- get the start time of the process
-- output is dd-hh:mm:ss if process has been stared few days ago
-- output is hh:mm:ss if process has been stared few hours ago
-- output is mm:ss if process has been stared few minutes or seconds ago
-- assumption is made that it just started few seconds ago
-- convert in seconds = mm*60 + ss
set runningTime to ((word 1 of paragraph 2 of PStext) as integer) * 60 + (word 2 of paragraph 2 of PStext) as integer
if runningTime < lastTime then
set lastTime to runningTime
set lastPID to unix id of aProc
set MyProc to aProc
end if
end repeat
if lastPID > 0 then -- if a process has been found
set the frontmost of MyProc to true -- set it in foreground
end if
end tell
I made several comments to make it clear about the "ps" command. If anyone knows how to get directly time in second from ps output, thanks. (I am quite sure there should be an easiest way !)

Applescript - How to run a single bash command from terminal and wait for response before continue?

I have a modelinfo.sh file, if I run it in Terminal it echos/saves results to a TXT file.
To execute this file from Terminal I use command:
./modelinfo.sh -s C8QH74G6DP11
With this command it saves results for given serialnumber: C8QH74G6DP11
I need to get reports for 5000 serials, so I think AppleScript might help me?
I have wrote this code with AppleScript:
tell application "Terminal"
do script ("./modelinfo.sh -s C8TJ14JWDP11") in window 1
do script ("./modelinfo.sh -s C8QH74G6DP12") in window 1
do script ("./modelinfo.sh -s C8QKGFWSDP13") in window 1
do script ("./modelinfo.sh -s C8QKFR5FDP14") in window 1
end tell
With this Code above my IP gets Blocked and I get only report for the first serialnumber.
I have also tried:
on delay duration
set endTime to (current date) + duration
repeat while (current date) is less than endTime
tell AppleScript to delay duration
end repeat
end delay
tell application "Terminal"
do script ("./modelinfo.sh -s C8TJ14JWDP11") in window 1
delay 20
do script ("./modelinfo.sh -s C8QH74G6DP12") in window 1
delay 20
do script ("./modelinfo.sh -s C8QKGFWSDP13") in window 1
delay 20
do script ("./modelinfo.sh -s C8QKFR5FDP14") in window 1
end tell
But this code doesn't help either..
Last I tried:
tell application "Terminal"
do script ("./modelinfo.sh -s C8TJ14JWDP11") in window 1
end tell
This last script I can run as many times as I want and I always gets the report without getting my IP blocked.
It looks like Applescript runs all 4 serials at once even I get IP blocked?
Since I am able to run single check multiple times without getting blocked.
Can anyone please help and point me in right direction?
Is it possible to this with Applescript?
Or can I make a new bash file which runs all my 5000 commands 1 by 1?
Thank you
Updated Answer
If you want to count the lines and give an indication of progress, replace the code below with this:
#!/bin/bash
declare -i total
total=$(wc -l <sn.txt) # count the lines in sn.txt
i=1
while read sn; do
echo "Fetching $sn ($i of $total)"
./modelinfo.sh -s "$sn"
((i++))
done < sn.txt
Original Answer
No idea why anyone would use Applescript for this - it is clearly a simple bash script to run from Terminal.
Assume your serial numbers are saved in a file called sn.txt like this:
C8QH74G6DP11
C8TJ14JWDP11
C8QH74G6DP12
C8QKGFWSDP13
You would then save the following in a file called fetch in your HOME directory. It reads your serial numbers one at a time and fetches them.
#!/bin/bash
while read sn; do
echo Fetching $sn...
./modelinfo.sh -s "$sn"
done < sn.txt
Then you would go into Terminal and type the following to make it executable:
chmod +x fetch
and then you can run it by typing
./fetch
You start Terminal by holding down Command and tapping the Spacebar then typing Ter and Spotlight will guess you mean Terminal, then you just hit Enter to actually start it.
Well, here is the common approach in Applescript to use the approach you are trying.
property serialList: {"C8TJ14JWDP11", "C8QH74G6DP12", "C8QKGFWSDP13", "C8QKFR5FDP14"}
tell application "Terminal"
repeat with aSerial in serialList
do script ("./modelinfo.sh -s " & aSerial) in window 1
delay 20
end
This should work. However, the state of the terminal window needs to be finished with the process and ready for the next call for this to work, so a delay of 20 may be too simplistic. Put the above coded inside a try block, to see any error.
try
-- above code goes here
on error err
display dialog err
end try
Another approach however, is to include the shell commands directly in an Applescript without going through the Terminal app, using
do shell script
You'll have to post the contents of your modelinfo.sh file to get a sense of that possibility.

Start console program from AppleScript and monitor it status

I attempted to start console program from AppleScript and restart when it crashes. I wrote this code
repeat
do shell script "/path/to/program"
end repeat
But it hangs and mac can`t reboot.
How can i put "do shell script" in another thread?
All you need to do is put a "&" character at the end of your command. That sends it to the background. However I would not use your code. That repeat loop will run forever and spawn new processes for as long as it runs. Your best bet would be to run a stay-open applescript which periodically checks if the process is running. If it isn't then the applescript could launch it. The repeat loop is not what you want. Try this code. Save it as an application and check the box for stay-open in the save window.
on run
end run
on idle
set runShellScript to false
tell application "System Events"
if not (exists process "processName") then
set runShellScript to true
end if
end tell
if runShellScript then do shell script "/path/to/program &"
return 30 -- the script will stop for 30 seconds then run again until you quit the applescript
end idle

Script to shutdown mac

I'm trying to automate the shutdown of my mac, I've tried the scheduled shutdown in energy saver and I wanna sleep but these don;t seem to work. VLC player runnign seems to prevent the shutdown. I think I need a script to forcefully shutdown the mac regardless of of what errors may thrown to screen by various programs running.
Thanks
Ok,
This is the applescript code im using to shutdown may mac. I've added it as an iCal event thats runs nightly.
tell application "System Events" to set the visible of every process to true
set white_list to {"Finder"}
try
tell application "Finder"
set process_list to the name of every process whose visible is true
end tell
repeat with i from 1 to (number of items in process_list)
set this_process to item i of the process_list
if this_process is not in white_list then
do shell script "killall \"" & this_process & "\""
end if
end repeat
on error
tell the current application to display dialog "An error has occurred!" & return & "This script will now quit" buttons {"Quit"} default button 1 with icon 0
end try
tell application "System Events"
shut down
end tell
Could you try a simple applescript, which goes something like this...
tell application "System Events"
shut down
end tell
See if it works, and then you can make it run through Automator at certain time, etc.
my solution (somwhat late). Just a bash script with apple in it:
#!/bin/bash
# OK, just shutdown all ... applications after n minutes
sudo shutdown -h +2 &
# Try normal shutdown in the meantime
osascript -e 'tell application "System Events" to shut down'
I also edited the /etc/sudoers (and /private/etc/sudoers) file(s) and added the line:
ALL=NOPASSWD: /sbin/shutdown
Always worked for me for an assured shutdown (knock knock ;-) )
This should do:
do shell script "shutdown" with administrator privileges
If you want to pass the admin password from key chain, with no prompt:
do shell script "shutdown" with administrator privileges password "password here"
But do not store the admin password in clear anywhere. Instead use the keychain access.
Alternatively you could kill all user processes, via:
do shell script "kill -9 -1"
This however would also kill your own Applescript process, preventing it from requesting the shutdown/restart afterwards.
Either way you're playing with fire, when using sudo or kill.
do what linux users do. use a bash script. if u dont know how to create one just go ahead and download ANY bash script u find using your internet search and open it with text edit app and paste the following:
( be careful if many people use the pc , then this method is not recommended, cause they can learn your user login password from inside this script )
#!/bin/bash
echo -n "Enter a number > "
read x
echo [your password] | sudo -S shutdown -h +$x
it will work the same way it works in linux. the terminal will pop up a message and ask you to enter a number. if we choose for exaple 50 , then the pc ( niresh ) or mac will shutdown in 50 minutes.

Sending commands and strings to Terminal.app with Applescript

I want to do something like this:
tell application "Terminal"
activate
do script "ssh user#server.com"
-- // write user's password
-- // write some linux commands to remote server
end tell
For example to log in to the server, enter the password, and then login to mysql and select a DB.
I type that every day and it would be really helpful to bundle it into a script.
Also, is there a reference of what commands, properties, functions, etc. do applications (Terminal, Finder, etc) have available to use within Applescript? thanks!
EDIT: Let me clear this up:
I don't want to do several 'do script' as I tried and doesn't work.
I want to open a Terminal window, and then emulate a human typing in some characters and hitting enter. Could be passwords, could be commands, whatever, just sending chars to the Terminal which happens to be running ssh. I tried keystroke and doesn't seem to work.
First connect to the server and wait for 6 seconds (you can change that) and then execute whatever you need on the remote server using the same tab
tell application "Terminal"
set currentTab to do script ("ssh user#server;")
delay 6
do script ("do something remote") in currentTab
end tell
As EvanK stated each do script line will open a new window however you can run two commands with the same do script by separating them with a semicolon. For example:
tell application "Terminal"
do script "date;time"
end tell
But the limit appears to be two commands.
However, you can append "in window 1" to the do script command (for every do script after the first one) to get the same effect and continue to run as many commands as you need to in the same window:
tell application "Terminal"
do script "date"
do script "time" in window 1
do script "who" in window 1
end tell
Note that I just used the who, date, and time command as an example...replace
with whatever commands you need.
Here's another way, but with the advantage that it launches Terminal, brings it to the front, and creates only one window.
I like this when I want to be neatly presented with the results of my script.
tell application "Terminal"
activate
set shell to do script "echo 1" in window 1
do script "echo 2" in shell
do script "echo 3" in shell
end tell
How about this? There's no need for key codes (at least in Lion, not sure about earlier), and a subroutine simplifies the main script.
The below script will ssh to localhost as user "me", enter password "myPassw0rd" after a 1 second delay, issue ls, delay 2 seconds, and then exit.
tell application "Terminal"
activate
my execCmd("ssh me#localhost", 1)
my execCmd("myPassw0rd", 0)
my execCmd("ls", 2)
my execCmd("exit", 0)
end tell
on execCmd(cmd, pause)
tell application "System Events"
tell application process "Terminal"
set frontmost to true
keystroke cmd
keystroke return
end tell
end tell
delay pause
end execCmd
You don't need to "tell" Terminal to do anything. AppleScript can do shell scripts directly.
set theDir to "~/Desktop/"
do shell script "touch " & theDir &"SomeFile.txt"
or whatever ...
Why don't use expect:
tell application "Terminal"
activate
set currentTab to do script ("expect -c 'spawn ssh user#IP; expect \"*?assword:*\"; send \"MySecretPass
\"; interact'")
end tell
Your question is specifically about how to get Applescript to do what
you want. But, for the particular example described, you might want
to look into 'expect' as a solution.
Kinda related, you might want to look at Shuttle (http://fitztrev.github.io/shuttle/), it's a SSH shortcut menu for OSX.
The last example get errors under 10.6.8 (Build 10K549) caused by the keyword "pause".
Replacing it by the word "wait" makes it work:
tell application "Terminal"
activate
my execCmd("ssh me#localhost", 1)
my execCmd("myPassw0rd", 0)
my execCmd("ls", 2)
my execCmd("exit", 0)
end tell
on execCmd(cmd, wait)
tell application "System Events"
tell application process "Terminal"
set frontmost to true
keystroke cmd
keystroke return
end tell
end tell
delay wait
end execCmd
I could be mistaken, but I think Applescript Terminal integration is a one-shot deal...That is, each do script call is like opening a different terminal window, so I don't think you can interact with it at all.
You could copy over the SSH public keys to prevent the password prompt, then execute all the commands joined together (warning: the following is totally untested):
tell application "Terminal"
activate
do script "ssh jdoe#example.com '/home/jdoe/dosomestuff.sh && /home/jdoe/dosomemorestuff.sh'"
end tell
Alternatively, you could wrap the ssh and subsequent commands in a shell script using Expect, and then call said shell script from your Applescript.
set up passwordless ssh (ssh-keygen, then add the key to ~/.ssh/authorized_keys on the server). Make an entry in ~/.ssh/config (on your desktop), so that when you run ssh mysqlserver, it goes to user#hostname... Or make a shell alias, like gotosql, that expands to ssh user#host -t 'mysql_client ...' to start the mysql client interactively on the server.
Then you probably do need someone else's answer to script the process after that, since I don't know how to set startup commands for mysql.
At least that keeps your ssh password out of the script!
Petruza,
Instead of using keystroke use key code.
The following example should work for you.
tell application "System Events"
tell application process "Terminal"
set frontmost to true
key code {2, 0, 17, 14}
keystroke return
end tell
end tell
The above example will send the characters {d a t e}
to Terminal and then keystroke return will enter and run
the command. Use the above example with whatever key codes you need
and you'll be able to do what you're trying to do.
what about something like this:
tell application "Terminal"
activate
do shell script "sudo dscl localhost -create /Local/Default/Hosts/cc.josmoe.com IPAddress 127.0.0.1"
do shell script "sudo dscl localhost -create /Local/Default/Hosts/cc.josmos2.com IPAddress 127.0.0.1"
end tell
As neat solution, try-
$ open -a /Applications/Utilities/Terminal.app *.py
or
$ open -b com.apple.terminal *.py
For the shell launched, you can go to Preferences > Shell > set it to exit if no error.
That's it.
I built this script. It is in Yosemite and it is bash script using AppleScript to choose a list of users for SSH servers. Basically you define an IP and then the user names.. when the application launches it asks who you want to login in as.. the SSH terminal is launched and logged in prompting a password...
(***
* --- --- --- --- ---
* JD Sports Fashion plc
* Apple Script
* Khaleel Mughal
* --- --- --- --- ---
* #SHELLSTAGINGSSHBASH
* --- --- --- --- ---
***)
set stagingIP to "192.162.999.999"
set faciaName to (choose from list {"admin", "marketing", "photography_cdn"})
if faciaName is false then
display dialog "No facia was selected." with icon stop buttons {"Exit"} default button {"Exit"}
else
set faciaName to (item 1 of faciaName)
tell application "Terminal"
activate
do script "ssh " & faciaName & "#" & stagingIP & ""
end tell
end if
I highly recommend though; Nathan Pickmans post above about Shuttle (http://fitztrev.github.io/shuttle/).. a very smart and simple application.

Resources