Home Backend Development Python Tutorial Python使用Paramiko模块编写脚本进行远程服务器操作

Python使用Paramiko模块编写脚本进行远程服务器操作

Jun 10, 2016 pm 03:04 PM
paramiko python

简介:
paramiko是python(2.2或更高)的模块,遵循SSH2协议实现了安全(加密和认证)连接远程机器。
安装所需软件包:
http://ftp.dlitz.net/pub/dlitz/crypto/pycrypto/pycrypto-2.5.tar.gz
http://www.lag.net/paramiko/download/paramiko-1.7.7.1.tar.gz

1

2

3

4

5

6

7

8

tar zxvf pycrypto-2.5.tar.gz

cd pycrypto-2.5

python setup.py build

python setup.py install

tar zxvf paramiko-1.7.7.1.tar.gz

cd paramiko-1.7.7.1

python setup.py build

python setup.py install

Copy after login

脚本简单编写:
管理单台服务器:

脚本一:查询172.16.22.23磁盘使用情况

1

2

3

4

5

6

7

8

9

10

11

12

13

#!/usr/bin/python

import paramiko

hostname="172.16.22.23"

port=22

username="root"

password="larryroot"

if __name__=="__main__":

    s=paramiko.SSHClient()

    s.set_missing_host_key_policy(paramiko.AutoAddPolicy())

    s.connect(hostname,port,username,password)

    stdin,stdout,sterr=s.exec_command("df -Th")

    print stdout.read()

    s.close()

Copy after login


脚本二:在远程服务器上执行相应命令

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

#!/usr/bin/python

#by larry

#2011/01/30

import sys

import paramiko

  

hostname=sys.argv[1]

command = " ".join(sys.argv[2:])

port=22

username="root"

password="larryroot"

if __name__=="__main__":

    s=paramiko.SSHClient()

    s.set_missing_host_key_policy(paramiko.AutoAddPolicy())

    s.connect(hostname,port,username,password)

    stdin,stdout,sterr=s.exec_command(command)

    print stdout.read()

    s.close()

Copy after login

使用方法:

1

2

python single1.py ip地址  命令

[root@localhost ~]# python single1.py 172.16.22.23 df -TH

Copy after login

1

2

3

4

5

6

7

8

9

10

11

Filesystem  Type   Size  Used Avail Use% Mounted on

/dev/sda2   ext3   13G  6.0G  5.7G 52% /

/dev/sda1   ext3   104M  12M  87M 13% /boot

tmpfs    tmpfs   61M   0  61M  0% /dev/shm

/dev/sda4   ext3   7.6G  465M  6.8G  7% /data

/dev/sdb1   ext3   32G  5.9G  25G 20% /autocd

[root@localhost ~]# python single1.py 172.16.22.23 free -m

total    used    free   shared  buffers   cached

Mem:      114    112     2     0     26     35

-/+ buffers/cache:     50     64

Swap:     1027     0    1027

Copy after login

脚本三:管理多台服务器:批量查询ip列表中对应服务器的磁盘使用情况

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

#!/usr/bin/python

#by larry

#2011/01/30

import paramiko

port=22

username="root"

file=open("ip.list")

for line in file:

    hostname=str(line.split("\t")[1])

    password=str(line.split("\t")[4]).strip()

    print "##########################",hostname,"########################"

    s=paramiko.SSHClient()

    s.set_missing_host_key_policy(paramiko.AutoAddPolicy())

    s.connect(hostname,port,username,password)

    stdin,stdout,sterr=s.exec_command("df -Th")

    print stdout.read()

    s.close()

file.close()

Copy after login

用法:

1

[root@localhost ~]# python ssh.py

Copy after login

1

2

3

4

5

6

7

8

9

10

11

12

13

############################ 172.16.22.22 ########################

Filesystem  Type  Size Used Avail Use% Mounted on

/dev/sda2   ext3   12G 5.6G 5.3G 52% /

/dev/sda1   ext3   99M  12M  83M 13% /boot

tmpfs    tmpfs   58M   0  58M  0% /dev/shm

/dev/sda4   ext3  7.1G 443M 6.3G  7% /data

/dev/sdb1   ext3   30G 5.5G  23G 20% /autocd

############################ 172.16.22.23 ########################

Filesystem  Type  Size Used Avail Use% Mounted on

/dev/sda2   ext3   15G 2.6G  11G 19% /

/dev/sda1   ext3   99M  12M  82M 13% /boot

tmpfs    tmpfs   60M   0  60M  0% /dev/shm

/dev/sda4   ext3   33G 377M  31G  2% /data

Copy after login

ip.list文件内容:

1

2

dx   172.16.22.22  22  root  larryroot

wt   172.16.22.23  22  root  larryroot

Copy after login

脚本四:类似于脚本二,在所有远程服务器上执行相应命令

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

#!/usr/bin/python

#by larry

#2011/01/30

import paramiko

import sys

port=22

username="root"

command = " ".join(sys.argv[1:])

file=open("ip.list")

for line in file:

    hostname=str(line.split("\t")[1])

    password=str(line.split("\t")[4]).strip()

    print "##################",hostname,"######################"

    s=paramiko.SSHClient()

    s.set_missing_host_key_policy(paramiko.AutoAddPolicy())

    s.connect(hostname,port,username,password)

    stdin,stdout,sterr=s.exec_command(command)

    print stdout.read()

    s.close()

file.close()

Copy after login


用法:

1

python ssh.py 命令

Copy after login

简单整理到这里通过python的paramiko模块可以很方便的管理服务器,文件的上传下载后续会整理出来。

SSH
下面是通过ssh的dsa或rsa公钥验证批量登录服务器执行命令:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

#!/usr/bin/python

#2012/02/02 by larry

import paramiko

import sys,os

port=22

username="larry"

key_file="~/.ssh/authorized_keys"

know_host="/home/larry/.ssh/known_hosts"

command=" ".join(sys.argv[1:]) ####获取命令行参数

file=open("ip.list")

for line in file:

    hostname=str(line.split(" ")[1]) ####截取ip字段

    print "#####################################",hostname,"###############################################"

    s=paramiko.SSHClient()

    s.set_missing_host_key_policy(paramiko.AutoAddPolicy())

    s.load_system_host_keys(know_host)

    s.connect(hostname,port,username,key_file)

    stdin,stdout,sterr=s.exec_command(command)

    print stdout.read().strip()

    s.close()

file.close()

Copy after login


执行python脚本:

1

python sshkey.py df -h

Copy after login

1

2

3

4

5

6

7

8

################172.16.22.22########################

Filesystem      Size Used Avail Use% Mounted on

/dev/mapper/VolGroup00-LogVol00

14G 3.5G 9.7G 27% /

/dev/mapper/VolGroup00-data

116G  47G  64G 43% /data

/dev/cciss/c0d0p1   99M  13M  82M 14% /boot

tmpfs         5.9G   0 5.9G  0% /dev/shm

Copy after login
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP and Python: Different Paradigms Explained PHP and Python: Different Paradigms Explained Apr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

Python vs. JavaScript: The Learning Curve and Ease of Use Python vs. JavaScript: The Learning Curve and Ease of Use Apr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Choosing Between PHP and Python: A Guide Choosing Between PHP and Python: A Guide Apr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

Can vs code run in Windows 8 Can vs code run in Windows 8 Apr 15, 2025 pm 07:24 PM

VS Code can run on Windows 8, but the experience may not be great. First make sure the system has been updated to the latest patch, then download the VS Code installation package that matches the system architecture and install it as prompted. After installation, be aware that some extensions may be incompatible with Windows 8 and need to look for alternative extensions or use newer Windows systems in a virtual machine. Install the necessary extensions to check whether they work properly. Although VS Code is feasible on Windows 8, it is recommended to upgrade to a newer Windows system for a better development experience and security.

Can visual studio code be used in python Can visual studio code be used in python Apr 15, 2025 pm 08:18 PM

VS Code can be used to write Python and provides many features that make it an ideal tool for developing Python applications. It allows users to: install Python extensions to get functions such as code completion, syntax highlighting, and debugging. Use the debugger to track code step by step, find and fix errors. Integrate Git for version control. Use code formatting tools to maintain code consistency. Use the Linting tool to spot potential problems ahead of time.

PHP and Python: A Deep Dive into Their History PHP and Python: A Deep Dive into Their History Apr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

How to run programs in terminal vscode How to run programs in terminal vscode Apr 15, 2025 pm 06:42 PM

In VS Code, you can run the program in the terminal through the following steps: Prepare the code and open the integrated terminal to ensure that the code directory is consistent with the terminal working directory. Select the run command according to the programming language (such as Python's python your_file_name.py) to check whether it runs successfully and resolve errors. Use the debugger to improve debugging efficiency.

Is the vscode extension malicious? Is the vscode extension malicious? Apr 15, 2025 pm 07:57 PM

VS Code extensions pose malicious risks, such as hiding malicious code, exploiting vulnerabilities, and masturbating as legitimate extensions. Methods to identify malicious extensions include: checking publishers, reading comments, checking code, and installing with caution. Security measures also include: security awareness, good habits, regular updates and antivirus software.

See all articles