1.安裝
(1)使用下面命令獲得最新版本的ssh4py安裝包
(1)使用下面命令獲得最新版本的ssh4py安裝包
git clone git://github.com/wallunit/ssh4py
(2)解壓ssh4py後使用下面命令進行安裝:
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"
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)
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')。
這裡我們都會發現,使用exec_command('cd dirname')時並不會切換目錄,
execute_command() 是a single session,每次執行完後都要回到預設目錄。
所以可以 .execute_command('cd /var; pwd')。