Python uses LIBSSH2 to connect to Linux

Source: Internet
Author: User

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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.