The landlord Python small white one, without any programming experience. Recent research Python automation operation and maintenance technology and best practices, today in the Look Paramiko module, according to gourd painting scoop, realized two small programs, share the following!
First, simply introduce the next Paramiko module. Paramiko is a python-based SSH2 remote secure connection, support authentication and key mode, implement remote command execution, file transfer, intermediate SSH proxy, etc., relative pexpect, the package hierarchy is higher, more close to the function of SSH protocol.
Install, with PIP installation, instructions are simple: Pip install Paramiko
Of course, the premise needs to be configured good PIP.
Nonsense not much to say, on the code:
1. Example 1:
The code reads the contents of the file in the current directory Commands.txt (the command to be executed by the file record), processes it, returns the list of command rows, and then invokes the Paramiko module-related method directly in the main () function, executes the command in the file sequentially, and prints out the output.
[Email protected] paramiko]# more simple1.py
#!/usr/bin/python
Import Sys
Import OS
Import Paramiko
def get_cmds (fp= ' commands.txt '):
If Os.path.isfile (FP) and Os.access (Fp,os. R_OK):
f = open (FP, ' RB ')
lines = F.readlines ()
F.close ()
Cmds = map (lambda X:x.rstrip (), lines)
Return Cmds
Else
Sys.exit ()
Return None
def main ():
If Len (sys.argv) = = 4:
host = SYS.ARGV[1]
user = sys.argv[2]
passwd = sys.argv[3]
else:
print " usage:%s Host user passwd "% (Sys.argv[0])
sys.exit ()
paramiko.util.log_to_file (' Syslogin.log ')
SSH = Paramiko. Sshclient ()
Ssh.set_missing_host_key_policy (Paramiko. Autoaddpolicy ())
Ssh.connect (Hostname=host,username=user,password = passwd)
Cmds = Get_cmds ()
For CMD in Cmds:
Stdin,stdout,stderr = Ssh.exec_command (cmd)
Print Stdout.read ()
Ssh.close ()
if __name__ = = "__main__":
Main ()
In this example, the contents of the Commands.txt file are as follows (you can write the command to this file according to your actual needs, without modifying the original code):
[Email protected] paramiko]# more Commands.txt
Free-m
Uptime
Uname-a
Df-h
W.H.O.
The command results are as follows:
[email protected] paramiko]#./simple1.py
usage:./simple1.py Host user passwd #远程server的主机名, username, password through command line parameter input, not given here, directly output the usage hint.
[Email protected] paramiko]#/simple1.py 192.168.0.200 root 123456
Total used free shared buff/cache available
mem:984 96 733 6 154 728
swap:3967 0 3967
18:33:17 up 1 day, 4:38, 1 user, load average:0.00, 0.01, 0.05
Linux admin-node 3.10.0-514.el7.x86_64 #1 SMP Tue Nov 16:42:41 UTC x86_64 x86_64 x86_64 gnu/linux
Filesystem Size used Avail use% mounted on
/dev/mapper/cl-root 36G 1.4G 34G 4%/
Devtmpfs 482M 0 482M 0%/dev
Tmpfs 493M 0 493M 0%/dev/shm
Tmpfs 493M 6.8M 486M 2%/run
Tmpfs 493M 0 493M 0%/sys/fs/cgroup
/DEV/SDA1 1014M 139M 876M 14%/boot
Tmpfs 99M 0 99M 0%/run/user/0
Root Tty1 2017-10-16 09:09
This example is simple, if you need to execute instructions on multiple servers at the same time, you can put the remote host information in the dictionary format into the list, through the loop to execute sequentially. No longer repeat here, the landlord himself has no code-related codes.
2. Example 2:
The code first filters out all files in a given directory with a subdirectory suffix of. py and stores the file name in a list, then packages the file through the Tar_files function and finally uploads the package file to the remote server through the Put_files function, and put_ The files function uses the Paramiko put method.
[Email protected] paramiko]# more simple2.py
#!/usr/bin/python
Import Sys
Import OS
Import Tarfile
Import datetime
Import Paramiko
def get_files (dir_path,files=[]):
For name in Os.listdir (Dir_path):
Full_path = Os.path.join (dir_path,name)
If Os.path.isfile (Full_path) and Os.path.splitext (Full_path) [1]== '. Py ':
Files.append (Full_path)
If Os.path.isdir (Full_path):
Get_files (Full_path,files)
return files
def tar_files (FILES,DST):
If Isinstance (files,list):
tar = Tarfile.open (DST, ' W:gz ')
For file in Files:
Tar.add (file)
Tar.close ()
Else
Sys.exit ()
def put_files (Host,user,passwd,localpath,remotepath):
Tran = Paramiko. Transport ((host,22))
Tran.connect (USERNAME=USER,PASSWORD=PASSWD)
SFTP = Paramiko. Sftpclient.from_transport (Tran)
Sftp.put (Localpath,remotepath)
Tran.close ()
def main ():
Try
Files = get_files ('/root/python ')
suffix = datetime.datetime.now (). Strftime ("%y%m%d%h%m")
DST = "/tmp/tar_%s.tar.gz"% (suffix)
Tar_files (FILES,DST)
RemotePath = DST
Put_files (' 192.168.0.200 ', ' root ', ' 123456 ', Dst,remotepath)
Except Exception,e:
Print str (e)
Sys.exit ()
if __name__ = = "__main__":
Main ()
Execute the script:
[Email protected] paramiko]#./simple2.py
Compressed files on the host side
[Email protected] tmp]# pwd
/tmp
[Email protected] tmp]# Ls-al *.tar.gz
-rw-r--r--1 root root 56884 Oct 17:55 tar_201710201755.tar.gz
-rw-r--r--1 root root 56884 Oct 18:41 tar_201710201841.tar.gz
-r--r--r--. 1 root root 60654199 Sep vmwaretools-9.6.0-1294478.tar.gz
Compressed files on the remote host:
[Email protected] ~]# cd/tmp
[Email protected] tmp]# Ls-al *.tar.gz
-rw-r--r--1 root root 27179 Oct 11:40 tar_201710161140.tar.gz
-rw-r--r--1 root root 27179 Oct 12:14 tar_201710161214.tar.gz
-rw-r--r--1 root root 56884 Oct 17:55 tar_201710201755.tar.gz
-rw-r--r--1 root root 56884 Oct 18:41 tar_201710201841.tar.gz
The perfect implementation of file compression and upload, haha!
Today only learned Paramiko Sshclient and sftpclient two classes, but also only to understand the most basic use method, follow-up study, and then update, with you to encourage each other!
This article is from the "Python Small White Advanced Road" blog, please be sure to keep this source http://ccczlb611.blog.51cto.com/3588825/1974706
Python small white Paramiko (1)