[英]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?
有什么线索吗?
The code below will do what you want and you can adapt it to your execute
function:下面的代码将执行您想要的操作,您可以将其调整为您的
execute
函数:
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()
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.但是请注意,该命令将默认为您的
$HOME
目录,因此您要么需要在$PATH
包含install.sh
,要么(很可能)您需要cd
到包含install.sh
脚本的目录.
You can check your default path with:您可以使用以下命令检查默认路径:
stdin, stdout, stderr = client.exec_command('getconf PATH')
print "PATH: ", stdout.readlines()
However, if it is not in your path you can cd
and execute the script like this:但是,如果它不在您的路径中,您可以像这样
cd
并执行脚本:
stdin, stdout, stderr = client.exec_command('(cd /path/to/files; ./install.sh)')
print "stderr: ", stderr.readlines()
print "pwd: ", stdout.readlines()
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.如果脚本不在您的
$PATH
您将需要使用./install.sh
而不是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:如果您在完成上述所有操作后仍然遇到问题,也可以检查
install.sh
文件的权限:
stdin, stdout, stderr = client.exec_command('ls -la install.sh')
print "permissions: ", stdout.readlines()
ssh = paramiko.client.SSHClient()
ssh.set_missing_host_key_policy(paramiko.client.AutoAddPolicy())
ssh.connect(hostname=host, username=username, password = password)
chan = ssh.invoke_shell()
def run_cmd(cmd):
print('='*30)
print('[CMD]', cmd)
chan.send(cmd + '\n')
time.sleep(2)
buff = ''
while chan.recv_ready():
print('Reading buffer')
resp = chan.recv(9999)
buff = resp.decode()
print(resp.decode())
if 'password' in buff:
time.sleep(1)
chan.send(password + '\n')
time.sleep(2)
print('Command was successful: ' + cmd)
subprocess.Popen('ssh thehost install.sh')
请参阅subprocess
模块。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.