The use of Python Paramiko modules __python

Source: Internet
Author: User
Tags ssh ssh server

Windows has many very good SSH clients, such as putty. In the Python world, you can create your own SSH client or server using the original socket and some cryptographic functions, but if you have a ready-made module, why do you want to implement it yourself? Using the Pycrypto in the Paramiko library allows you to easily use the SSH2 protocol.

Paramiko installation Method There are many such posts on the web, not described here. This is mainly about how to use it. Paramiko implementation of SSH2 is achieved from two perspectives: SSH client and server.

First let us clarify the following nouns: sshclient: Packaging Channel, Transport, sftpclient Channel: is a kind of socket, a secure SSH transmission channel; Transport: is an encrypted session (but such an object has not been created) and creates an encrypted tunnels, the tunnels is called Channel, which is the object that the client maintains a connection with the server. Start the session with Connect ()/start_client ()/start_server ().

Refer to Paramiko's library documentation: Http://docs.paramiko.org/en/2.0/index.html Below are some common usage cases:

SSH client Implementation one, execute remote command

This scheme directly uses the Exec_command () of the Sshclient object to execute commands on the server, following the specific code:

    #实例化SSHClient
    client = Paramiko. Sshclient ()
    #自动添加策略 to save the server hostname and key information
    Client.set_missing_host_key_policy (Paramiko. Autoaddpolicy ())
    #连接SSH服务端, authenticated by user name and password
    client.connect (ip,username=user,password=passwd)
    # Open a channel and execute the command
    stdin,stdout,stderr = client.exec_command (command)
    #打印执行结果
    print stdout.readlines ()
    #关闭SSHClient
    client.close ()

SSH Client Implementation scenario Two, remote command execution

The solution is to get a transport object to the Sshclient object, to transport the Exec_command () of the object to execute the command on the server, and the following is the specific code:

#实例化SSHClient
client = Paramiko. Sshclient ()
#自动添加策略 to save the server hostname and key information
Client.set_missing_host_key_policy (Paramiko. Autoaddpolicy ())
#连接SSH服务端, authenticated by user name and password
client.connect (ip,username=user,password=passwd)
# Instantiate the transport and establish session sessions
Ssh_session = Client.get_transport (). Open_session ()
if ssh_session.active:
    Ssh_session.exec_command (command)
    print SSH_SESSION.RECV (1024)
client.close ()

implementation of SSH service side

The implementation of SSH server must inherit Serverinterface, and implement the corresponding methods inside. The specific code is as follows:

Import Socket import SYS import threading import Paramiko Host_key = Paramiko. Rsakey (filename= ' Private_key.key ') class Server (Paramiko. Serverinterface): def __init__ (self): the #执行start_server () method triggers the event first, and Is_active returns True if the return succeeds self.event = th Reading. Event () #当is_active返回True, enter the authentication phase Def check_auth_password (self, username, password): if (username = = ' Roo T ') and (password = = ' 123456 '): Return Paramiko. Auth_successful return Paramiko. Auth_failed #当认证成功, the client requests to open a channel def check_channel_request (self, Kind, Chanid): If kind = ' Sessio N ': Return Paramiko. open_succeeded #命令行接收ip与port server = sys.argv[1] ssh_port = Int (sys.argv[2]) #建立socket Try:sock = Socket.socket (Soc Ket.af_inet, Socket. SOCK_STREAM) #TCP socket sock.setsockopt (socket. Sol_socket, SOCKET. SO_REUSEADDR, 1) sock.bind ((server, ssh_port)) sock.listen print ' [+] listening for connection ...
    .' Client, addr= Sock.accept () except Exception, E:print ' [-] Listen failed: ' + str (e) sys.exit (1) print ' [+] Got a connection! ' Try: #用sock. Accept () returns the socket instantiation transport bhsession = Paramiko.
        Transport (client) #添加一个RSA密钥加密会话 Bhsession.add_server_key (host_key) server = Server () Try: #启动SSH服务端 Bhsession.start_server (server=server) except Paramiko. Sshexception, X:print ' [-] SSH negotiation failed ' chan = bhsession.accept print ' [+] authenticated! ' Print CHAN.RECV (1024) chan.send ("Welcome to Me ssh") while True:try:command = Raw_inpu T ("Enter Command:"). Strip ("\ n") if command!= ' exit ': Chan.send (command) prin
                T CHAN.RECV (1024) + ' \ n ' else:chan.send (' exit ') print ' exiting ' Bhsession.close () Raise Exception (' exit ') except KeyboardInterrupt:bhSession.close () ExcePT Exception, E:print ' [-] caught Exception: ' + str (e) try:bhSession.close () Except:pass
 Sys.exit (1)

uploading files using SFTP

Import Paramiko
#获取Transport实例
tran = Paramiko. Transport ("Host_ip")
#连接SSH服务端
tran.connect (username = "username", password = "password")
# Gets the SFTP instance
sftp = Paramiko. Sftpclient.from_transport (Tran)
#设置上传的本地/remote file path
localpath= "/root/desktop/python/newnc.py"
Remotepath= "/tmp/newnc.py"
#执行上传动作
sftp.put (localpath,remotepath)

tran.close ()

downloading files using sftp

Import Paramiko

#获取SSHClient实例
client = Paramiko. Sshclient ()
client.set_missing_host_key_policy (Paramiko. Autoaddpolicy ())
#连接SSH服务端
client.connect ("Host_ip", username= "username", password= "password")
# Gets the transport instance
Tran = Client.get_transport ()
#获取SFTP实例
sftp = Paramiko. Sftpclient.from_transport (Tran)

remotepath= '/tmp/newnc.py '

localpath= '/root/desktop/newnc.py ' Sftp.get (RemotePath, LocalPath)

client.close ()
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.