Open OSX application command line solution bypassing graphical admin password - macos

I have made an automator application which runs a couple scripts (and does not use any GUI, but it is opening a GUI for admin password because of my use of with administrator privileges). The main script is started using
do shell script (quoted form of myCommand) with administrator privileges
Because of this, when executing the application, a graphical admin password prompt is presented.
I am trying to execute this application automatically after install via bash and am wondering how I would be able to bypass the GUI password prompt; I'm looking for a way to execute the application via bash and run it silently (no GUI, no password prompt).
Because of the with administrator privileges all the common
sudo open -a /Application/appname.app &
sudo osascript -e 'tell app id "com.app.bundleid"' -e activate -e end
even running as root all still bring up the GUI password prompt.
Is there any way to open an application supplying the GUI password prompt via bash for OSX? Or is there a better way I should have executed the main script rather than do shell script (quoted form of myCommand) with administrator privileges?

If access for assistive devices has been enabled, you can use GUI scripting to interact with the password dialogs:
tell application "System Events" to tell process "SecurityAgent"
set value of text field 2 of scroll area 1 of group 1 of window 1 to "pa55word"
click button 2 of group 2 of window 1
end tell
osascript -e 'do shell script "ls ~root" with administrator privileges' &
sleep 1
osascript -e 'tell application "System Events" to tell process "SecurityAgent"
set value of text field 2 of scroll area 1 of group 1 of window 1 to "pa55word"
click button 2 of group 2 of window 1
end tell'
Normally for example sudo open -a Finder doesn't open Finder as root, but sudo /System/Library/CoreServices/Finder.app/Contents/MacOS/Finder does.

I see in your comment to your question that you will enter a password in your script. This is not a good idea. If you need to use a password in a script you can use the keychain to store the password and have the script retrieve it. This is a secure way to store your passwords because if you put the password in an applescript it is stored in clear text and thus can be easily retireved by anyone.
Create the password item - Open Keychain Access application and select the keychain in the left column. Then click File>New Password Item..., give it a name, account name (can be anything), and enter the password. You can "get info" on the item and change the Kind to "generic key" to differentiate it from other passwords if you want.
NOTE: You must put the name you have given the item into the passwordItemName variable in the code
When you run this code a dialog will pop up asking if you want to allow access to the item. If you click "always allow" then you will prevent this dialog from coming up again in the future. Or you can prevent this dialog altogether by getting info on the keychain item, going to the access control tab, and adding the "security" binary in the "always allow access..." section.
-- global variables are often saved in a writable applescript
-- so we ensure it's a local variable to prevent this
local pword
set pword to getPW()
do shell script "/path/to/script/file.sh" user name "adminusershortname" password pword with administrator privileges
on getPW()
set passwordItemName to "ApplescriptAdminPass"
do shell script "/usr/bin/security find-generic-password -wl " & quoted form of passwordItemName
end getPW

The way in which I was able to bypass the GUI password prompt and still use with administrator privileges was to recompile the Automator app and supply the user and password in-line:
on run {input, parameters}
set myCommand to POSIX path of ((path to me as string) & "Contents:Resources:script_name.sh")
do shell script (quoted form of myCommand) user name "local-admin" password "local-adminpassword" with administrator privileges
return input
end run
This accomplishes running the Applescript as with admin privileges, but without popping up the GUI password prompt. The app then runs silently, as I needed, and runs the script script_name.sh which in turn runs many other scripts and copies over other resource files out of (from myapp.app/Contents/Resources/) into system directories etcetera.
For the record, I needed it to act this way because I am deploying this app using Munki and wanted it to automatically run silently after install using a postinstall script:
#!/bin/bash
open -b "com.company.bundleidformyapp"
exit 0

Related

macOS - Switch to admin user when running a shell script as a root user

So, I have this name.sh script with bunch of shell commands.
I need to change the wallpaper before ending that script.
I'm using
osascript -e 'tell application "System Events.app" to set picture of every desktop to "/Library/Desktop Pictures/my.jpg"'
at the end of the line. The thing is the Apple Script won't run under root. Because System Events will throw 10810 at first and then 600 (Application isn't running). If I run this osascript under admin user, it will work just fine. The wallpaper will be set.
Let me know how you guys can help me in this!
If you are already root, you have full privileges to switch to a different user account at any time. The command for that is su.
If your user is admin,
su - admin <<\:
osascript -e 'tell application "System Events.app" to set picture of every desktop to "/Library/Desktop Pictures/dneg.jpg"'
:
There are various ways to pass the command as standard input to su; perhaps see also Pass commands as input to another command (su, ssh, sh, etc)

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.

How to "do shell script with administrator privileges" as a regular user and not as root?

I'm running an applscript that runs a shellscript through Terminal.
I want to be able to use "do shell script with administrator privileges" but the Terminal runs my script as root, and not as regular user (which is an Admin).
The reason I want to run not as root (except for the obvious reasons) is that I use the ~ sign so any user can log in and run the script locally (f.e. I write a log file straight to the user's Desktop).
The other reason I want to run not as root is because I use a ViseX installer during my shell script that does not run well as root.
This is the applescript I use (Thanks to regulus6633 for the applescirpt):
set theFile to "myscriptname.sh"
-- launch the application with admin privileges and get the pid of it
set thePID to (do shell script "/Applications/Utilities/Terminal.app/Contents/MacOS/Terminal > /dev/null 2>&1 & echo $!" with administrator privileges) as integer
-- get the bundle identifier of that pid so we can do something with the application
delay 0.2
tell application "System Events"
set theProcess to first process whose unix id is thePID
set bi to bundle identifier of theProcess
end tell
-- runs the Terminal with the shellscript
set theFileAlias to (POSIX file theFile) as alias
tell application id bi
activate
open theFileAlias
end tell
I have found approach to get success with next:
do shell script "sudo -H -u virtustilus /bin/bash -c \"/bin/bash -c '. ~/.bash_profile; /Users/vis/my_big_script.sh > /Users/vis/someLog.log 2>&1'\"" with administrator privileges
What is going here:
Start shell script with 'root' user (administrator privileges).
Change user to "virtustilus" (my main user) and change home directory too (flag -H).
Load . ~/.bash_profile environment variables (like a PATH).
Start script my_big_script.sh with redirected all output to the file someLog.log.
It works (I'm using it in automator application now).
Unfortunately, with administrator privileges means "as root". In Mac OS X, as in most other Unix-derived operating systems, there's no way to get administrator privileges as a non-root user. When you run something via sudo, it just runs the command as root.
You don't need to run an entire Terminal window as root, though. Just launch Terminal as the regular user and tell it (via do script inside a tell application "Terminal" block) to execute just the desired command as root. I don't know offhand if do script accepts with administrator privileges, but if not, you can always stick a sudo on the front.

Calling applescript from shell script using admin previleges

I'm running a shell script that runs an installation program (by ViseX) and selects different items in the installer through a list.
The installer needs administrator privileges to run properly, but I don't want to use sudo.
Currently the installation application does not work properly because it does not run with admin privileges.
How do I call the applescript with admin privileges or tell the installation app inside the applescript to run as admin?
Here's the applescript I'm using:
osascript <<-END
tell application "$1"
with timeout of 8 * 3600 seconds
activate
Select "$2"
DoInstall
end timeout
end tell
END
You can run shell scripts from an Applescript as an admin: see this technote.
So if you create this applescript as a separate script you could use it. Ugly, but should work.
Here's an applescript that does that. I'll leave you to turn it into a shell command. The following script opens the host file on your computer using TextEdit. You'll notice that admin privileges are required to open that file thus it makes for a good example. Note that I could do this particular task easier, but I'm doing it this way to show you how to launch an application with admin privileges and then target that application so you can perform other applescript commands...
set theFile to "/private/etc/hosts"
-- launch the application with admin privileges and get the pid of it
set thePID to (do shell script "/Applications/TextEdit.app/Contents/MacOS/TextEdit > /dev/null 2>&1 & echo $!" with administrator privileges) as integer
-- get the bundle identifier of that pid so we can do something with the application
delay 0.2
tell application "System Events"
set theProcess to first process whose unix id is thePID
set bi to bundle identifier of theProcess
end tell
-- do something with it eg. open the hosts file
set theFileAlias to (POSIX file theFile) as alias
tell application id bi
activate
open theFileAlias
end tell
do shell script "[path/to/app] [param]" user name "[admin name]" password "[password]" with administrator privileges

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