Python implementation Batch remote execution command (fortress machine)

Source: Internet
Author: User
Tags stdin ssh port

Python remote Batch execution

I am not a professional development, I have been learning Linux operations, for Python is also very short-time, so the code is not very simple to write.

Some time ago a classmate to me to do an automated operation and maintenance platform, I do not understand the Python Django, and for the HTML and JS this kind of development learning has not been involved, so I said I do some backstage implementation, the front end will be given to my classmates to do . No nonsense, next I do the idea of batch execution.

    1. Module used: Paramiko
    2. Function: Very simple is the batch execution command, similar to ansible, originally want to use fabric, but think of or use Paramiko, because I in learning ansible,ansible inside there is Paramiko. Later, the host group inside the configuration file will be put into the database. Here I would like to use MongoDB because my host profile is written in the form of a dictionary, which is more convenient to save in the document database.
    3. Configuration file format: here in order to facilitate access to information, directly written in the form of a dictionary, originally wanted to use the Pickle module to serialize input into the file, but later found that if the host if more, manual input or too troublesome.
    4. Class: In order to better add functionality later, I directly write Paramiko sshclient as a class. Later to add the upload text, download and other functions, which used the function of SFTP.
    5. Function: This function is to conditionally output the file and find the name of the host group that matches.
    6. Explain the next Paramiko:paramiko module in my understanding is to rely on SSH remote module.

(1), Paramiko installation method: use PIP installation.

(2), Paramiko core Components-----sshclient

Sshclient uses SSH's channel implementation and host connection and command execution.

sshclient methods < strong> parameters and parameter descriptions
Connect (for SSH connection and checksum)

Hostname: Destination host address

Port: Host port

Username: User name of the checksum

Password: login password

Pkey: Private key authentication

Key_filename: File name for private key authentication

Timeout: Connection time-out setting

Allow_agent: This is a Boolean, set to False when the use of SSH proxy

Look_for_keys: is also a Boolean, prohibit under. SSH to find the private key file

Compress: Set compression

exec_command (Remote execution command)

Stdin,stdout,stderr: These three are standard inputs, outputs, errors, which are used to get command execution results, and are not calculated as parameters of the method

Command: The string that executes the command, with double quotation marks.

BufSize: File buffer size, default is 1

 

load_system_host_keys (load local public key file) FileName: Specifies the public key record file for the remote host
set_missing_host_key_policy (the remote host does not have a key)

Autoaddpolicy: Automatically add host name and host key to local Hostkeys object

Rejectpolicy: auto-deny unknown hostname and key (default)

Warningpolicy: Accept Unknown host, But there will be a warning

(3) Paramiko Core Components Sftpclient class

Implementation of remote file operations, such as upload, download, permissions, status, and so on.

Methods of the Sftpclient class Parameter and parameter description
From_transport (using an SFTP client channel that has already been connected) T: Using a transferred object that has already been validated
Put (upload local file to SFTP server)

LocalPath: path to local file

RemotePath: Remote Path

Callback: Gets the number of bytes received and the total number of bytes transferred

Confirm: whether the stat () method is called after the file has been uploaded to determine the file size

Get (download files from the SFTP server to local)

RemotePath: File path to be downloaded

LocalPath: Saving the local file path

Callback: the same as put.

mkdir: Resume Catalogue

Remove: Delete

Rename: Renaming

Stat: Get remote File information

Listdir: Gets the specified directory list

      (4), there is a use of Invoke_shell often used
 Invoke_shell (*args, **kwds) Request an interactive shell session on the This channel. If the server allows it, the channel would then is directly connected to the stdin, stdout,  and   stderr of the shell. Normally would call Get_pty before this,  in  which case the shell would opera  Te through the Pty, and  the channel would be a connected to the stdin and   stdout of the Pty. When the shell exits, the channel would be closed  and  can ' t is reused. You must open a new channel if  you wish to open another shell. 

Requests an interactive shell session on this channel, and if the service allows it, the channel will connect directly to standard input, standard input, and the wrong shell, and usually we call Get_pty's usage before using it, so that the shell session is handled through a pseudo-terminal, And the session is connected to standard input and output, and when our shell exits, the channel shuts down and can be used again, and you have to reopen the other shell.

      (4) Practice Fortress Machine (excerpt from Liu Tians's "Python Automation Operations")
#Defining Server Informationhostname ="192.168.0.158"username="Root"Password="aixocm"#defining the logon log and password promptPort = 22Passinfo='\ ' s password:'Paramiko.util.log_to_file ('Syslogin.log')#Login to the fortress machine, automatically add Hostkeys information to the hostSSH =Paramiko. Sshclient () Ssh.set_missing_host_key_policy (Paramiko. Autoaddpolicy ()) Ssh.connect (hostname=blip,username=bluser,password=blpasswd)#Create a sessionChannel =Ssh.invoke_shell () channel.settimeout (100)#channel execution shell SSH connectionBuff ="'resp="'Channel.send ('SSH'+username+'@'+hostname+'\ n') while  notBuff.endswith (passinfo):Try: Resp= CHANNEL.RECV (9999)   exceptexception,e:Print 'Error info:%s connection time.'%(str (e)) Channel.close () Ssh.close () sys.exit () Buff+=respif  notBuff.find ('yes/no') = =-1: Channel.send ('yes\n') Buff="'channel.send (Password+'\ n') Buff="' while  notBuff.endswith ('# '): Resp= CHANNEL.RECV (9999)    if  notResp.find (passinfo) = =-1:       Print 'Error info:authentication failed.'channel.close () ssh.close ( )
View Code

    1. configuration file: code:

{"hostname":"web","host_ip": [  "192.168.0.157","192.168.0.158","  192.168.0.159"]}

Class:#!/usr/bin/env pyth#coding:utf-8import Paramiko

classaction (object):def __init__(self, IP, username, command):Self. IP =IPSelf.username =usernameSelf.command =CommanddefSsh_connect (self):SSH=Paramiko. Sshclient ()Ssh.set_missing_host_key_policy (Paramiko. Autoaddpolicy ())Try: Ssh.connect (hostname=self. IP, Username=self.username)Stdin,stdout,stderr=ssh.exec_command (Self.command) Print "######################>%s <####################"%(self.) IP)PrintStderr.read ()PrintStdout.read () ssh.close ()

exceptexception,e:Print "######################>%s <####################"%(self.) IP)Print

To execute the main function:

From simple1 Import action
defget_values (hostname): Conf_file=open ('scn.conf','R') Lines=Conf_file.readlines () forLineinchLines:line= Line.strip ("\ n") Line=eval (line)ifhostname = = line["hostname"]: return(line) Breakconf_file.close ()if __name__=="__main__": hostname= Raw_input ("Write your hostname:") Username= Raw_input ("Write your username:") Command= Raw_input ("Write your excute command:") Host=get_values (hostname)HOST_IP = List (host["host_ip"]) forIinchRange (0,len (HOST_IP)): Conn=Action (Host_ip[i],username,command) Conn.ssh_connect ()

Note that I did not add password and port,port SSH Port 22nd, which is used by default, password I use Ssh-keygen and Ssh-copy-id to login without a password directly.

Python implementation Batch remote execution command (fortress machine)

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.