(1)使用下面命令获得最新版本的ssh4py安装包
import socket
import libssh2
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect(('exmaple.com', 22))
session = libssh2.Session()
session.startup(sock)
#还需要使用基本的密码进行验证登陆
session.userauth_password(username, password)
#现在可以开始使用它了
channel = session.channel()
channel.execute('ls /etc/debian_version')
channel.wait_closed()
if channel.get_exit_status() == 0:
print "It's a Debian system"
else:
print "It's not a Debian system"
import socket
import libssh2
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect(('exmaple.com', 22))
session = libssh2.Session()
session.startup(sock)
#还需要使用基本的密码进行验证登陆
session.userauth_password(username, password)
channel = session.channel()
channel.execute('ls -l')
stdout = []
stderr = []
while not channel.eof:
data = channel.read(1024)
if data:
stdout.append(data)
data = channel.read(1024, libssh2.STDERR)
if data:
stderr.append(data)
print ''.join(stdout)
print ''.join(stderr)
这里我们都会发现,使用exec_command('cd dirname')时并不会切换目录,
execute_command() 是a single session,每次执行完后都要回到缺省目录。
所以可以 .execute_command('cd /var; pwd')。