Python op Wizi Paramiko

Source: Internet
Author: User
Tags readline socket error stdin ssh server port ssh server git clone

Paramiko is a module written in the Python language that follows the SSH2 protocol and supports remote connection to the server in an encrypted and authenticated manner. 1. Install the Pycrypto module first before installing Paramiko. The setup script is:

git clone https://github.com/dlitz/pycrypto.git
cd pycrypto && sudo python setup.py install
CD.
git clone https://github.com/paramiko/paramiko.git
cd Paramiko && sudo python setup.py install
CD.
sudo rm-rf pycrypto Paramiko


2. Use of ParamikoThe most basic class in the Paramiko API is "Paramiko." Sshclient ". It provides the most basic interface to server connection and file transfer. One of the simplest examples:
Import Paramiko

ssh = Paramiko. Sshclient ()
ssh.connect (' 127.0.0.1 ', username = ' Ubuntu ', password= ' 123 ')
It will create a new sshclient instance and then call Connect () to join the local SSH service, which is no simpler than that.
HOST KeysSSH authentication Another way is to use the key. Whenever you use SSH to connect to a remote server, the host key's information is automatically stored in the ". Ssh/known_hosts" file in the home directory. If you connect to a host via SSH, you will see the following information:
The authenticity of host ' localhost (:: 1) ' Can ' t be
established.
RSA key fingerprint is 
22:fb:16:3c:24:7f:60:99:4f:f4:57:d6:d1:09:9e:28.
Are you sure your want to continue connecting 

Typing "yes", the key information will be saved to the "known_hosts" file. These keys are important because they are a trust mechanism with the host. If the key is corrupted or changed, the client will reject the connection and will not notify you, and Paramiko will use the same rule. If the relevant information is not saved in "Hnown_hosts", the sshclient default behavior is to reject the connection. This would be incredibly annoying if you were working in an experimental environment where the system was installed over and over again. The method for setting the rule invocation of the host key is called the "Set_missing_host_key_policy ()" Of the SSH client instance, which sets the method you expect to manage the host key. If you are as lazy as I am, you can use "Paramiko." Autoaddpolicy () method to automatically receive the unknown key:
Import Paramiko

ssh = Paramiko. Sshclient ()
ssh.set_missing_host_key_policy (Paramiko. Autoaddpolicy ())
ssh.connect (' 127.0.0.1 ', username = ' Ubuntu ', password= ' 123 ')

Connect MethodConnect (hostname, port=22, Username=none, Password=none, Pkey=none, Key_filename=none, Timeout=none, allow _agent=true, Look_for_keys=true, Compress=false, Sock=none, Gss_auth=false, Gss_kex=false, gss_deleg_creds=True , Gss_host=none, Banner_timeout=none)
Parameters hostname(str) –the server to connect to
Port(int) –the server port to connect to
username(str) –the username to authenticate as (defaults to the current local username)
Password(str) –a password to use for authentication or for unlocking a private key
Pkey(. Pkey) –an optional private key to a for authentication
Key_filename(str) –the filename, or list of filenames, of optional private key (s) to try for authentication
Timeout(float) –an optional timeout (in seconds) for the "TCP Connect"
allow_agent(bool) –set to False to disable connecting to the SSH agent
Look_for_keys(bool) –set to False to disable searching for discoverable private key files in ~/.ssh/
Compress(bool) –set to True to turn on compression
sock(socket) –an open socket or Socket-like object (such as a Channel) to use for communication to the target host
Gss_auth(bool) –true if you want to use GSS-API authentication
Gss_kex(bool) –perform Gss-api Key Exchange and user authentication
gss_deleg_creds(BOOL) –delegate GSS-API client credentials or not
Gss_host(str) –the targets name in the Kerberos database. Default:hostname
Banner_timeout(float) –an optional timeout (in seconds) to wait for the SSH banner to be presented.
Raises badhostkeyexception –if The server ' s host key could not being verified
authenticationexception –if authentication failed
sshexception –if There is any other error connecting or establishing a SSH session
Socket.error –if A socket error occurred while connecting


Connect to SSH service and authenticate. The host key is checked against the system host key (Load_system_host_keys ()) and the local host key (Load_host_keys ()). If no relevant information is found in the system host key and in the local host key, an unknown host key policy (Set_missing_host_key_policy) is used. Authentication failure throws Sshexception exception. Authentication priority is: The Pkey or Key_filename passed in (if any) any key we can find through a SSH agent any "Id_rsa", "ID_DSA" or "id _ECDSA "key discoverable in ~/.ssh/plain Username/password auth, if a password is given Key_filename and Pkey one on the line. If the private key requires a password to unlock, indicate the password parameter, such as:

Ssh.connect (' 10.227.129.234 ', username= ' ubuntu ', compress = True, key_filename= '/home/ubuntu/.ssh/test.pem ', password= ' 123 ')

If you want to Hide Password, what to do each time you have to interact with it. Can look at the official demo inside the example of the Getpass module to hide the input password:
Import getpass

key_filename = '/home/ubuntu/.ssh/test.pem '
try:
	key = Paramiko. Rsakey.from_private_key_file (key_filename)
except Paramiko. Passwordrequiredexception:
	password = getpass.getpass (' RSA key password: ')
	Pkey = Paramiko. Rsakey.from_private_key_file (path, password)
	
ssh = Paramiko. Sshclien ()
ssh.connect (' 10.227.129.234 ', username= ' ubuntu ', compress = True, pkey= pkey)
Here clearly indicates that Pkey is the RSA encryption method, if it is DSS encryption, the Rsakey will be changed to Dsskey can be, through the private key file in the first line of the description information automatically determine whether the RSA encryption or DSS encryption.
If Isinstance (key_filename,str):
            key_file=open (Key_filename, ' R ')
            Key_head=key_file.readline ()
            Key_ File.seek (0)
            if ' DSA ' in Key_head:
                Keytype=paramiko. Dsskey
            elif ' RSA ' in Key_head:
                Keytype=paramiko. Rsakey

Execute CommandExec_command (Command, Bufsize=-1, Timeout=none, Get_pty=false)

Execute a command on the SSH server. A New Channel is opened and the requested command is executed. The command ' s input and output streams are returned as Pythonfile-like objects representing stdin, stdout, and stderr.

Parameters Command (str) –the command to execute
bufsize (int) –interpreted the same way as by the built-in file () function in Python
Timeout (int) –set command ' s channel timeout. SeeChannel.settimeout.settimeout
Returns The stdin, stdout, and stderr of the executing command, as a 3-tuple
Raises sshexception:If the server fails to execute the command
Now that you are connected, you can execute some commands and return the results of the command execution. Like other unix-like applications, SSH uses input, output, and error to make inputs, outputs, and incorrect output. Error will be output to standard error output, output to standard output, if you want to send data back to the application, write the data to the standard input.
...
>>> ssh.connect (' 127.0.0.1 ', Username= ' Jesse ', password= ' lol ')
>>> stdin, stdout, stderr = Ssh.exec_command ("uptime")
>>> type (stdin)
paramiko.channel.ChannelFile
>>> Stdout.readlines ()
[' 13:35 up one days  ,  3:13, 4 users, load averages:0.14 0.18 0.16\n ']

In this case, Paramiko opens a new "Paramiko." Channel "instance, which represents a secure channel to connect to a remote machine, and the Channel instance behaves the same as the Python socket instance. When we call the "Exec_command ()" method, the channel instance opens, "Paramiko. Channelfile "and" File-like "instances represent data sent to and from the remote machine.
Channelfile, which is returned from the remote machine, uses "read ()" in standard output and standard error output to continuously display the content. If too much data is returned and the buffer is filled, the wait program reads. In this case, neither "readlines ()" nor "read ()" is invoked. If you want to hold this data internally, you can use "ReadLine" to iterate.
For a system-managed task, the same need to analyze the output of executing commands, thanks to Python's powerful string-handling capabilities, is a piece of cake, isn't it? Let's run and name it, but it takes a password:
stdin, stdout, stderr = Ssh.exec_command ("sudo dmesg")

Oh ..., the sudo command is used here. The remote host will require me to enter a password in interactive mode, so don't worry:
Ssh.connect (' 127.0.0.1 ', Username= ' Jesse ', password= ' lol ')
stdin, stdout, stderr = Ssh.exec_command ("sudo fdisk-l ")
stdin.write (' lol\n ')
Stdin.flush ()
data = Stdout.read (). Splitlines () for line in
data:
    if Line:
        Print Line

See it. I logged on to the remote machine and executed the sudo command. The key point here is that when you need to enter a password, I write password to stdin. You may be confused, and this is a simple and basic way to create your own interactive shell. You may want to use the traditional Python cmd module to execute the admin command to manage the machine, which is simple in Paramiko. In the following example, an easy way to do this is to: we encapsulate Paramiko operations into the RunCommand method, allowing users to add hosts (hosts) at will, call Connect and execute commands.

#!/usr/bin/python Import Paramiko Import cmd class RunCommand (cmd.
        CMD): "" "Add_host simple Shell to run a command on the host" "prompt = ' ssh > ' def __init__ (self):
        Cmd.cmd.__init__ (self) self.hosts = [] Self.connections = [] def do_add_host (self, args):
            "" "" "Add the host to the host list" "If Args:self.hosts.append (Args.split (', ')) Else:
		
        Print "Usage:host" Def do_connect (self, args): "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" For host in self.hosts:client = Paramiko. Sshclient () Client.set_missing_host_key_policy (Paramiko. 
            Autoaddpolicy ()) Client.connect (Host[0], username=host[1], password=host[2]) Self.connections.append (client) def do_run (self, Command): "" "Execute this command on the all hosts In the list "" If command:forHost, conn in Zip (self.hosts, self.connections): stdin, stdout, stderr = conn.exec_command (command)  Stdin.close () for line in Stdout.read (). Splitlines (): print ' Host:%s:%s '% (Host[0], line) else:print "Usage:run" def do_close (self, args): for Conn in Self.con Nections:conn.close () if __name__ = = ' __main__ ': RunCommand (). Cmdloop ()
Output:
SSH > Add_host 127.0.0.1,jesse,lol
ssh > Connect
ssh > Run uptime
host:127.0.0.1:14:49 up one  da Ys,  4:27, 8 users,
load averages:0.36 0.25 0.19
ssh > Close
This example merely demonstrates the concept of a pseudo-interactive shell, and there are many things to be done with it: Better print multiline stdout output, handle standard errors, add an end method, threading the returned command/data, and so on. As with all shells, when you need to visualize data, the upper limit is limited. such as Pssh, OSH, fabric and other tools, management returned data methods are not the same, they have different ways to aggregate output from different hosts.
InteractiveInvoke_shell (term= ' vt100 ', width=80, height=24, width_pixels=0, height_pixels=0)

Start an interactive shell sessions on the SSH server. A New

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.