简体   繁体   English

Ruby Net / SSH exec-获取远程进程的pid

[英]Ruby Net/SSH exec - get pid of remote process

I am launching a nohup remote script with Ruby Net/SSH. 我正在使用Ruby Net / SSH启动nohup远程脚本。

Net::SSH.start(ip_address, user, options) do |ssh|
  script = File.join(remote_path, 'run_case.py')
  cmd = "nohup python #{script} #{args}  < /dev/null &"
  ssh.exec(cmd)
end

All stdout and stderr is saved to a file on the remote machine. 所有的stdoutstderr都保存到远程计算机上的文件中。

Is it possible to get the PID of the remote script so that I can kill it if needed? 是否可以获取远程脚本的PID,以便在需要时可以将其杀死?

EDIT 1: I have modified the script as suggested. 编辑1:我已经按照建议修改了脚本。

Net::SSH.start(ip_address, user, options) do |ssh|
  script = File.join(remote_path, 'run_case.py')
  cmd = "nohup python #{script} #{args}  < /dev/null & echo $! > save_pid.txt"
  ssh.exec(cmd)
  pid = ssh.exec!("cat save_pid.txt")
  puts mesh_pid
end

It complains that it cannot find the file. 它抱怨找不到文件。 Is this because the file does not exist yet? 这是因为文件尚不存在吗? I would prefer to avoid any sleep command if possible 我希望尽可能避免使用任何sleep命令

EDIT 2: Maybe this is not elegant but it works. 编辑2:也许这不是优雅,但它的工作原理。 I have created a second ssh session and used pgrep . 我创建了第二个ssh会话并使用了pgrep

Net::SSH.start(ip_address, user, options) do |ssh|
  script = File.join(remote_path, 'run_case.py')
  cmd = "nohup python #{script} #{args}  < /dev/null &"
  ssh.exec(cmd)
end

Net::SSH.start(ip_address, user, options) do |ssh|
  cmd = "python #{script} #{args}"
  mesh_pid = ssh.exec!("pgrep -f '#{cmd}'")
  puts mesh_pid
end

You should be able to determine the PID (and store it in a file) as follows: 您应该能够确定PID(并将其存储在文件中),如下所示:

Net::SSH.start(ip_address, user, options) do |ssh|
  script = File.join(remote_path, 'run_case.py')
  cmd = "nohup python #{script} #{args}  < /dev/null & echo $! > save_pid.txt"
  ssh.exec(cmd)
end

In a script, $! 在脚本中,$! represents the PID of the last process executed. 表示最后执行的进程的PID。 If you need to kill the process, you can do it via: 如果您需要终止该过程,可以通过以下方法完成:

kill -9 `cat save_pid.txt`
rm save_pid.txt

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM