MAC OS - AppleScript - 如何使其显示一次用户名和密码对话框?

问题描述 投票:0回答:3

你好,

在我的 AppleScript 中,我运行以下代码,

do shell script "sudo networksetup -setproxybypassdomains Ethernet *.local, 169.254/16"
do shell script "sudo networksetup -setwebproxy Ethernet 127.0.0.1 8888"
do shell script "sudo networksetup -setsecurewebproxy Ethernet 127.0.0.1 8888"

但是每次都要求输入密码。我的意思是,当脚本打开时,每行进程都会要求输入 3 次密码。为了防止询问密码,我必须在终端中输入以下内容,

sudo chmod u+s /usr/sbin/networksetup

按下 Enter 键时,它会要求输入密码,一旦输入并运行 AppleScript,则不再要求输入密码(3 次)。

但是用户必须转到终端并输入上述命令。为了防止这种情况,我在 AppleScript 中使用了以下代码,

do shell script "sudo chmod u+s /usr/sbin/networksetup"

因此用户运行AppleScript,它将自动设置。但我收到以下错误消息,

enter image description here

如何更改AppleScript,

do shell script "sudo chmod u+s /usr/sbin/networksetup"

...使其要求输入密码一次,然后执行其余的“...do shell script...”部分而不要求输入密码。或者添加密码以及上面的代码行以使其工作?

macos shell applescript sudo
3个回答
5
投票

您看过“do shell script”命令的定义吗?您不将 sudo 与该命令一起使用。您可以使用“具有管理员权限”,并且如果您愿意,可以提供“用户名”和“密码”。

执行此操作...打开 AppleScript 编辑器。在“文件”菜单下选择“打开词典”。从对话框窗口中选择 StandardAdditions.osax。在字典的搜索字段中搜索“do shell script”以查看您可以使用该命令执行的所有操作。

例如,以下是如何使用它。祝你好运。

do shell script "networksetup -setproxybypassdomains Ethernet *.local, 169.254/16" with administrator privileges

0
投票

您可以将密码作为参数传递给

sudo
。从手册页:

-S          The -S (stdin) option causes sudo to read the password from
                   the standard input instead of the terminal device.  The
                   password must be followed by a newline character.

0
投票

对旧问题的新答案,但由于没有答案包括保留名称和密码以及在输入过程中正确隐藏密码,这可能有助于吸引该问题的人。这两者都完成,然后在类似于OP的shell脚本中使用名称和密码。名称和密码存储为脚本的属性,但保持不可见。如果脚本发生更改,它们会自动“删除”,并且仅在第一次运行时需要重新输入。如果名称或密码不正确,则脚本会正常退出,然后再继续执行任何后续代码。 shell 脚本中不需要“sudo”,只要“以管理员权限”运行即可。通常,只需“以管理员权限”运行就会强制弹出窗口询问用户名和密码。但由于它们已包含在本示例中,因此脚本会默默地应用存储的名称和密码,并且首次运行后不会出现弹出窗口。

----------ENTER NAME & PASSWORD ONCE----------
property admin : null --resets to null after each edit
property pswrd : null --resets to null after each edit*
repeat
try
if admin is null then set admin to (text returned of (display dialog "Enter username:" default answer "")) --get name.
if pswrd is null then set pswrd to (text returned of (display dialog "Enter password for " & admin & ":" default answer "" with hidden answer)) --get pw.
do shell script "whoami" user name admin password pswrd with administrator privileges --test name & pw.
exit repeat --name & pw were OK!
on error err
set {admin, pswrd} to {null, null}
if err is "User canceled." then return err
display dialog err with icon 0
end try
end repeat
--beyond this line, admin-name & password are retained in the admin & pswrd properties!
----------EXAMPLE OF NAME & PASSWORD USEAGE----------
do shell script "networksetup -listallhardwareports" user name admin password pswrd with administrator privileges

© www.soinside.com 2019 - 2024. All rights reserved.