<p>你使用pexpect甚至paramiko有什么原因吗?</p>
<p>如果您设置了一个<a href="http://www.thegeekstuff.com/2008/11/3-steps-to-perform-ssh-login-without-password-using-ssh-keygen-ssh-copy-id/" rel="nofollow">public/private</a>键,那么您只需使用一个示例:</p>
<pre><code>command = "scp user@20.20.20.20:/home/user/tarfile.tar.gz"
split_command = shlex.split(command)
subprocess.call(split_command)
</code></pre>
<p>然后按照上面的建议使用paramiko发送命令。</p>
<p>您也可以使用keyfile:</p>
<p>以下类方法将为您提供一个持久会话(尽管它未经测试):</p>
<pre><code>#!/usr/bin/python
# -*- coding: utf-8 -*-
from __future__ import print_function
import os
from paramiko import SSHClient, AutoAddPolicy, AuthenticationException, RSAKey
from subprocess import call
class CommsSuite(object):
def __init__(self):
self.ssh_client = SSHClient()
#--------------------------------------
def _session_send(command):
"""
Use to send commands over ssh in a 'interactive_session'
Verifies session is present
If the interactive_session is not present then print the failed command.
This may be updated to raise an error,
which would probably make more sense.
@param command: the command to send across as a string
::TODO:: consider raise exception here as failed
session will most likely be fatal.
"""
if self.session.send_ready():
self.session.send("%s\n" % command)
else:
print("Session cannot send %s" % command)
#--------------------------------------
def _get_persistent_session(_timeout = 5):
"""
connect to the host and establish an interactive session.
@param _timeout: sets the timout to prevent blocking.
"""
privatekeyfile = os.path.expanduser('~/.ssh/id_rsa')#this must point to your keyfile
private_key = RSAKey.from_private_key_file(privatekeyfile)
self.ssh_client.set_missing_host_key_policy(AutoAddPolicy())
self.ssh_client.connect(hostname,
username = <username>,
pkey = private_key,
timeout = _timeout)
self.transport = self.ssh_client.get_transport()
self.session = self.transport.open_session()
self.session.exec_command("bash -s")
_get_persistent_session()
# build a comma seperated list of commands here as a string "[a,b,c]"
commands = ["tar -zxvf tarfile.tar.gz bin/installer.sh", "setsid /tmp/bin/installer.sh /tmp/tarfile.tar.gz > /dev/null 2>&1"]
# then run the list of commands
if len(commands) > 0:
for command in commands:
_session_send(command)
self.session.close()#close the session when done
CommsSuite()
</code></pre>