1. Installation
(1) Use the following command to obtain the latest version of the Ssh4py installation package git clone git://github.com/wallunit/ssh4py (2) after extracting the ssh4py, use the following command to install: CD ssh4py
Python setup.py Build
Python setup.py install 2. Get Started (1) in order to use LIBSSH2, you must create a low-level socket on your own and pass it to a new session object. #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) if you want to get the output of the execution command #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 (1024x768, Libssh2. STDERR)
If data:
Stderr.append (data)
print '. Join (STDOUT)
print '. Join (STDERR) (3) Problems that may be encountered in use
Here we will find that using Exec_command (' CD dirname ') does not switch directories,
Execute_command () is a single session, which is returned to the default directory after each execution.
So can. Execute_command (' Cd/var; pwd ').
Python uses LIBSSH2 to connect to Linux