python--------------paramiko远程控制模块学习(批量执行linux机器多条命令)

import paramiko
def sshExeCMD():
ssh_client=paramiko.SSHClient()
ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh_client.connect(hostname="192.168.8.200",port=22,username="root",password="123")
stdin,stdout,stderr = ssh_client.exec_command("cat /etc/redhat-release;hostname;ls /")

print(str(stdout.read()))

ssh_client.close()


if __name__ == '__main__':
   sshExeCMD()
=======================================================================================================================
另外一种写法:
# coding=utf-8
import paramiko

# 创建SSH对象
ssh = paramiko.SSHClient()
# 允许连接不在know_hosts文件中的主机
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
# 连接服务器
ssh.connect(hostname='192.168.8.200', port=22, username='root', password='123')

# 执行命令 exec_command('ls')
stdin, stdout, stderr = ssh.exec_command("cat ssh.sh")
# 获取命令结果
result = stdout.read()
print(result)

实现效果:

 

 

/var/log/secure日志记录

var

 密码的坑:

 

 第二种情况:

关机状态:

 显示:TimeoutError: [WinError 10060] 由于连接方在一段时间后没有正确答复或连接的主机没有反应,连接尝试失败。

 第三种情况:/etc/ssh/sshd_config限制了root登陆

 

 @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@

@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@

@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@

多个机器批量执行linux命令::

# 此脚本用于在多个机器上批量执行一个命令
import paramiko
# 用于执行远程命令
def exec_remote_cmd(cmd,hostname="",username="root",passwd="123",port="22"):
# 创建一个ssh对象
ssh_client=paramiko.SSHClient()
# 如果是第一次通过ip连接,会出现yes或者no,可以解决此问题
ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy)
ssh_client.connect(hostname=hostname,port=22,username=username,password=passwd)
stdin,stdout,stderr=ssh_client.exec_command(cmd)
print(stdout.read().decode('utf-8'))
ssh_client.close()

# exec_remote_cmd('free -h','192.168.204.128','root','redhat','22')


with open(file="C:/Users/Administrator/Desktop/host.txt")as f:
for line in f:
line=line.strip()
hostname,username,password,port=line.split(',')
# print(line.split(','))
print(hostname + " cmd result:###############################")
exec_remote_cmd('df -h;hostname;cat /etc/redhat-release;systemctl status mysqld;netstat -ntulp',hostname,username,password,port)


在写好python之后,还要准备在桌面上准备个文件

 





实现效果

192.168.8.200 cmd result:###############################
Filesystem Size Used Avail Use% Mounted on
devtmpfs 475M 0 475M 0% /dev
tmpfs 487M 0 487M 0% /dev/shm
tmpfs 487M 7.6M 479M 2% /run
tmpfs 487M 0 487M 0% /sys/fs/cgroup
/dev/mapper/centos-root 17G 4.9G 13G 29% /
/dev/sda1 1014M 138M 877M 14% /boot
zabbix-agent
CentOS Linux release 7.9.2009 (Core)
● mysqld.service - MySQL Server
Loaded: loaded (/usr/lib/systemd/system/mysqld.service; enabled; vendor preset: disabled)
Active: active (running) since Mon 2023-11-06 10:41:38 CST; 23h ago
Docs: man:mysqld(8)
http://dev.mysql.com/doc/refman/en/using-systemd.html
Process: 903 ExecStartPre=/usr/bin/mysqld_pre_systemd (code=exited, status=0/SUCCESS)
Main PID: 936 (mysqld)
Status: "Server is operational"
CGroup: /system.slice/mysqld.service
└─936 /usr/sbin/mysqld

Nov 06 10:41:27 zabbix-agent systemd[1]: Starting MySQL Server...
Nov 06 10:41:38 zabbix-agent systemd[1]: Started MySQL Server.
Active Internet connections (only servers)
Proto Recv-Q Send-Q Local Address Foreign Address State PID/Program name
tcp 0 0 0.0.0.0:22 0.0.0.0:* LISTEN 2507/sshd: /usr/sbi
tcp6 0 0 :::22 :::* LISTEN 2507/sshd: /usr/sbi
tcp6 0 0 :::33060 :::* LISTEN 936/mysqld
tcp6 0 0 :::3306 :::* LISTEN 936/mysqld

192.168.8.200 cmd result:###############################
Filesystem Size Used Avail Use% Mounted on
devtmpfs 475M 0 475M 0% /dev
tmpfs 487M 0 487M 0% /dev/shm
tmpfs 487M 7.6M 479M 2% /run
tmpfs 487M 0 487M 0% /sys/fs/cgroup
/dev/mapper/centos-root 17G 4.9G 13G 29% /
/dev/sda1 1014M 138M 877M 14% /boot
zabbix-agent
CentOS Linux release 7.9.2009 (Core)
● mysqld.service - MySQL Server
Loaded: loaded (/usr/lib/systemd/system/mysqld.service; enabled; vendor preset: disabled)
Active: active (running) since Mon 2023-11-06 10:41:38 CST; 23h ago
Docs: man:mysqld(8)
http://dev.mysql.com/doc/refman/en/using-systemd.html
Process: 903 ExecStartPre=/usr/bin/mysqld_pre_systemd (code=exited, status=0/SUCCESS)
Main PID: 936 (mysqld)
Status: "Server is operational"
CGroup: /system.slice/mysqld.service
└─936 /usr/sbin/mysqld

Nov 06 10:41:27 zabbix-agent systemd[1]: Starting MySQL Server...
Nov 06 10:41:38 zabbix-agent systemd[1]: Started MySQL Server.
Active Internet connections (only servers)
Proto Recv-Q Send-Q Local Address Foreign Address State PID/Program name
tcp 0 0 0.0.0.0:22 0.0.0.0:* LISTEN 2507/sshd: /usr/sbi
tcp6 0 0 :::22 :::* LISTEN 2507/sshd: /usr/sbi
tcp6 0 0 :::33060 :::* LISTEN 936/mysqld
tcp6 0 0 :::3306 :::* LISTEN 936/mysqld

192.168.8.101 cmd result:###############################
Filesystem Size Used Avail Use% Mounted on
devtmpfs 475M 0 475M 0% /dev
tmpfs 487M 0 487M 0% /dev/shm
tmpfs 487M 7.8M 479M 2% /run
tmpfs 487M 0 487M 0% /sys/fs/cgroup
/dev/mapper/centos-root 17G 1.5G 16G 9% /
/dev/sda1 1014M 138M 877M 14% /boot
tmpfs 98M 0 98M 0% /run/user/0
source
CentOS Linux release 7.9.2009 (Core)
Active Internet connections (only servers)
Proto Recv-Q Send-Q Local Address Foreign Address State PID/Program name
tcp 0 0 0.0.0.0:22 0.0.0.0:* LISTEN 1337/sshd
tcp 0 0 127.0.0.1:25 0.0.0.0:* LISTEN 1018/master
tcp6 0 0 :::22 :::* LISTEN 1337/sshd
tcp6 0 0 ::1:25 :::* LISTEN 1018/master


Process finished with exit code 0

##########python远程执行linux脚本###################(结果回车显示,不堆在一行显示)

 

import paramiko

cmd = '{0}/{1} linux 32'.format('/root/installer', 'make_client_installer.sh')
print(cmd)
try:
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect('192.168.8.101', 22, 'root', '123', timeout=5)
stdin, stdout, stderr = ssh.exec_command(cmd, get_pty=True)
while not stdout.channel.exit_status_ready():
result = stdout.readline()
print(result)
if stdout.channel.exit_status_ready():
a = stdout.readlines()
print(a)
break
ssh.close()
except Exception as e:
print(e)
实现效果如下:
执行权限:
chmod +x make_client_installer.sh

[root@source installer]# pwd
/root/installer
[root@source installer]# cat make_client_installer.sh
#!/bin/bash
echo "##############$(date +%Y-%m-%d-%H:%M:%S):主机巡检开始###################"
hostname
ifconfig
df -h
cat /etc/redhat-release
echo "##############$(date +%Y-%m-%d-%H:%M:%S):主机巡检结束###################"

[root@source installer]#

G:\Python3.8解释器\python.exe C:/Users/Administrator/PycharmProjects/pythonProject/2222.py
/root/installer/make_client_installer.sh linux 32
##############2023-11-08-16:07:11:主机巡检开始###################

source

eth0: flags=4163<UP,BROADCAST,RUNNING,MULTICAST> mtu 1500

inet 192.168.8.101 netmask 255.255.255.0 broadcast 192.168.8.255

inet6 fe80::4a97:b3a4:ffa8:5164 prefixlen 64 scopeid 0x20<link>

ether 00:0c:29:cb:46:bb txqueuelen 1000 (Ethernet)

RX packets 73075 bytes 67888637 (64.7 MiB)

RX errors 0 dropped 0 overruns 0 frame 0

TX packets 21533 bytes 3853686 (3.6 MiB)

TX errors 0 dropped 0 overruns 0 carrier 0 collisions 0

 

lo: flags=73<UP,LOOPBACK,RUNNING> mtu 65536

inet 127.0.0.1 netmask 255.0.0.0

inet6 ::1 prefixlen 128 scopeid 0x10<host>

loop txqueuelen 1000 (Local Loopback)

RX packets 4621 bytes 4663820 (4.4 MiB)

RX errors 0 dropped 0 overruns 0 frame 0

TX packets 4621 bytes 4663820 (4.4 MiB)

TX errors 0 dropped 0 overruns 0 carrier 0 collisions 0

 

Filesystem Size Used Avail Use% Mounted on

devtmpfs 475M 0 475M 0% /dev

tmpfs 487M 0 487M 0% /dev/shm

tmpfs 487M 14M 473M 3% /run

tmpfs 487M 0 487M 0% /sys/fs/cgroup

/dev/mapper/centos-root 17G 1.7G 16G 10% /

/dev/sda1 1014M 138M 877M 14% /boot

tmpfs 98M 0 98M 0% /run/user/0

CentOS Linux release 7.9.2009 (Core)

##############2023-11-08-16:07:11:主机巡检结束###################

[]

Process finished with exit code 0

 

posted @ 2023-11-06 21:30  往事已成昨天  阅读(108)  评论(0编辑  收藏  举报