简体   繁体   English

如何使用 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?有什么线索吗?

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.

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