Linux Shell脚本,kill作为另一个用户



最近我一直在尝试让这个脚本工作:

#!/usr/bin/expect -f
set pssword [lrange $argv 0 0]
spawn su - kod -c cd cod4 -c "nohup kill 7938"  > /dev/null 2>&1 &
expect "Password:" { send "$psswordr" }
expect "# " { send "q" }
exit

它应该以名为"kod"的用户登录并通过特定的pid终止进程

这是开始脚本,它工作得很好…

#!/usr/bin/expect -f
set pssword [lrange $argv 0 0]
set port [lrange $argv 1 1]
set mod [lrange $argv 2 2]
set map [lrange $argv 3 3]
set num [lrange $argv 4 4]
set hostname [lrange $argv 5 5]
set rcon [lrange $argv 6 6]
set password [lrange $argv 7 7]
spawn su - kod -c cd cod4 -c "nohup ./cod4_lnxded +set s_num=$num +set net_port $port +set dedicated 2 +set fs_game mods/$mod +set sv_punkbuster 1 +set sv_hostname $hostname +set rcon_password $rcon +set g_password $password +set promod_mode match_mr10 +set g_gametype sd +map $map"  > /dev/null 2>&1 &
expect "Password:" { send "$psswordr" }
expect "# " { send "q" }
exit

请不要告诉我"以root身份登录"或"使用sudo",因为这不是情况…谢谢!

我认为运行进程的用户和想要终止进程的用户应该在同一个组中。进程权限也应该与该组相关联。

真正的问题是您的代码正在丢弃可能来自该(相当复杂)命令的任何错误消息;如果您能够立即将这些信息打印出来或将其记录到文件中,那将会好得多。这样,您就可以诊断问题,而不必胡乱猜测……

还有其他问题。

  • 你用nohup包裹kill,但这真的是不必要的,因为发送信号几乎是即时的,你不想要额外的复杂性。
  • 您将密码作为命令行参数传递。这是不安全的,因为任何进程都可以读取传递给任何程序的整个命令行。最好从命令行上命名的文件中提取密码;如果您设置权限正确,那么只有您(和root)可以读取密码(这是OK的)。
  • 在提取命令行参数时使用lrange;这几乎肯定是错误的(lindex命令是一个更好的选择,或者甚至可能是lassign一次提取许多值,只要它在Tcl 8.5或更高版本中运行)。
  • 您正在硬编码进程ID。这几乎肯定不是你想做的,因为随着时间的推移,它很可能会有所不同。

通过这一小部分排序,我得到了这个可能改进的脚本:

#!/usr/bin/expect -f
# A more robust method for handling arguments than you had...
if {$argc == 0} {
    error "usage: $argv0 pid ?passFile?"
}
set pid [lindex $argv 0]
if {$argc > 1} {
    set passwordFile [lindex $argv 1]
} else {
    # Sensible default
    set passwordFile ~/.codPassword
}
# Read the password from the file
set f [open $passwordFile]
gets $f pssword
close $f
# Run the program (doesn't need the 'cd') with trap to supply password,
# and connect to user for error passthrough
spawn su - kod -c kill $pid
expect_background {
    "Password:" {exp_send "$psswordr"}
}
interact {eof close}

进一步思考,问题提出很久之后,另一个问题是:

spawn su - kod -c cd cod4 -c "nohup kill 7938"  > /dev/null 2>&1 &

那极有可能是在做一些奇怪和意想不到的事情。相反,您可能需要这样做:

spawn su -c "cd cod4; nohup kill 7938 > /dev/null 2>&1 &" - kod

这是因为您希望将所有这些内容作为一个shell脚本传递到su运行的shell中。

相关内容

最新更新