如何使用 SSH 在 Python 中远程执行脚本? [英] How to execute a script remotely in Python using SSH?
问题描述
def execute(self,command):
to_exec = self.transport.open_session()
to_exec.exec_command(command)
print 'Command executed'
connection.execute("install.sh")
当我检查远程系统时,我发现脚本没有运行.有什么线索吗?
When I check the remote system, I found the script didn't run. Any clue?
推荐答案
下面的代码会做你想做的,你可以将它调整到你的 execute
函数:
The code below will do what you want and you can adapt it to your execute
function:
from paramiko import SSHClient
host="hostname"
user="username"
client = SSHClient()
client.load_system_host_keys()
client.connect(host, username=user)
stdin, stdout, stderr = client.exec_command('./install.sh')
print "stderr: ", stderr.readlines()
print "pwd: ", stdout.readlines()
但请注意,该命令将默认为您的 $HOME
目录,因此您需要在 $PATH<中有
install.sh
/code> 或(很可能)您需要 cd
到包含 install.sh
脚本的目录.
Note, though, that commands will default to your $HOME
directory, so you'll either need to have install.sh
in your $PATH
or (most likely) you'll need to cd
to the directory that contains the install.sh
script.
您可以通过以下方式检查默认路径:
You can check your default path with:
stdin, stdout, stderr = client.exec_command('getconf PATH')
print "PATH: ", stdout.readlines()
但是,如果它不在您的路径中,您可以cd
并像这样执行脚本:
However, if it is not in your path you can cd
and execute the script like this:
stdin, stdout, stderr = client.exec_command('(cd /path/to/files; ./install.sh)')
print "stderr: ", stderr.readlines()
print "pwd: ", stdout.readlines()
如果脚本不在您的$PATH
中,您将需要使用 ./install.sh
而不是 install.sh
,就像你在命令行上一样.
If the script is not in your$PATH
you'll need to use ./install.sh
instead of install.sh
, just like you would if you were on the command line.
如果您在完成上述所有操作后仍然遇到问题,也可以检查 install.sh
文件的权限:
If you are still having problems after everything above it might also be good to check the permissions of the install.sh
file, too:
stdin, stdout, stderr = client.exec_command('ls -la install.sh')
print "permissions: ", stdout.readlines()
这篇关于如何使用 SSH 在 Python 中远程执行脚本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!