如何在Python中通过SSH远程执行脚本?
def execute(self,command):
to_exec = self.transport.open_session()
to_exec.exec_command(command)
print 'Command executed'
connection.execute("install.sh")
当我检查远程系统时,发现脚本没有运行。有什么线索吗?
3 个回答
-3
subprocess.Popen('ssh thehost install.sh')
可以看看这个subprocess
模块。
0
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)
当然可以!请把你想要翻译的内容发给我,我会帮你用简单易懂的语言解释清楚。
23
下面的代码可以满足你的需求,你可以根据自己的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()
不过要注意,命令默认会在你的$HOME
目录下运行,所以你需要确保install.sh
在你的$PATH
中,或者(更可能的情况)你需要cd
到包含install.sh
脚本的目录。
你可以用以下命令检查你的默认路径:
stdin, stdout, stderr = client.exec_command('getconf PATH')
print "PATH: ", stdout.readlines()
但是,如果它不在你的路径中,你可以这样cd
并执行脚本:
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
,就像你在命令行中一样。
如果你在尝试了以上所有方法后仍然遇到问题,检查一下install.sh
文件的权限也是个好主意:
stdin, stdout, stderr = client.exec_command('ls -la install.sh')
print "permissions: ", stdout.readlines()