Python SSH命令

2024-04-27 00:31:25 发布

您现在位置:Python中文网/ 问答频道 /正文

我有以下代码:

def executeRemoteCommand(host, command):
    cmd = "ssh " + host + " \'" + command + "\'"
    print cmd
    subprocess.check_call(cmd)

当我运行命令时:

java -Xss515m -Xms48g -Xmx48g -XX:+UseConcMarkSweepGC -XX:+PrintGCDetails -XX:+PrintGCTimeStamps -jar /local/experiments/helloworld/ro/server.jar /local/experiments/helloworld/ro/properties.json

使用上面的函数,我得到以下错误

File "./util/ssh_util.py", line 85, in executeRemoteCommand
    subprocess.check_call(cmd)
  File "/usr/lib/python2.7/subprocess.py", line 506, in check_call
    retcode = call(*popenargs, **kwargs)
  File "/usr/lib/python2.7/subprocess.py", line 493, in call
    return Popen(*popenargs, **kwargs).wait()
  File "/usr/lib/python2.7/subprocess.py", line 679, in __init__
    errread, errwrite)
  File "/usr/lib/python2.7/subprocess.py", line 1259, in _execute_child
    raise child_exception
OSError: [Errno 2] No such file or directory.

但是,当我直接在命令行中键入调用时,它可以正常工作。你知道吗

ssh foo92 'java -Xss515m -Xms48g -Xmx48g -XX:+UseConcMarkSweepGC -XX:+PrintGCDetails -XX:+PrintGCTimeStamps -jar /local/experiments/helloworld/ro/server.jar /local/experiments/helloworld/ro/properties.json'

有人知道吗?你知道吗


Tags: inpycmdrolibusrlocalline
0条回答
网友
1楼 · 发布于 2024-04-27 00:31:25

您需要设置shell=True以通过shell执行该命令:

subprocess.check_call(cmd, shell=True)

如果将参数作为列表传入,则可以直接执行它,而不是将其推入shell;这样,您也不必担心引用命令:

def executeRemoteCommand(host, command):
    subprocess.check_call(['ssh', host, command])

注意这里的hostcommand都是传递给ssh的单参数。通常,这就是shell将参数传递到ssh命令的方式,这就是java ...命令行周围的引号对的作用。你知道吗

相关问题 更多 >