您的位置:首页 > 运维架构 > Linux

python使用libssh2连接linux

2015-08-16 22:25 519 查看
1.安装
(1)使用下面命令获得最新版本的ssh4py安装包
git clone git://github.com/wallunit/ssh4py
(2)解压ssh4py后使用下面命令进行安装:
cd ssh4py
python setup.py build
python setup.py install
2.开始使用
(1)为了使用libssh2,你必须建立一个在您自己的的低级套接字并把它传递到一个新的Session对象。
#encoding: utf-8
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"
(2)假如你想获得执行命令的输出
#encoding: utf-8
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)
(3)使用中可能遇到的问题
这里我们都会发现,使用exec_command('cd dirname')时并不会切换目录,
execute_command() 是a single session,每次执行完后都要回到缺省目录。
所以可以 .execute_command('cd /var; pwd')。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: