execl数据复制到 ips.txt:
10.252.52.10 Linux Server private 4 1 cn2icon001
10.252.52.11 Linux Server private 4 0 cn2icon002
10.252.52.12 Linux Server private 4 0 cn2icon003
10.252.52.13 Linux Server private 4 0 cn2icon004
10.252.53.14 Linux Server private 4 0 cn2icon005
...
paramiko远程登录服务器并交互执行命令
import paramiko
def ssh_server(server):
ip, hostname = server[0], server[1]
client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
try:
client.connect(hostname=ip, username='icon', password=r'123456\\')
except Exception as e:
print(str(e))
with open("login_failed_servers.txt", "a") as f:
f.write("{} \n".format(' '.join(server)))
print('Recorded the server: {}'.format(' '.join(server)))
return
# 执行命令
# client.exec_command('pwd;cd /home;cat /etc/hosts')
# stdin,stdout, stderr = client.exec_command('hostname')
# result=stdout.read().decode('utf-8')
# print(result)
# client.close()
# 在远程服务器上生成新的交互式shell
ssh = client.invoke_shell()
time.sleep(0.2)
ssh.send('sudo su \n')
# 查看shell的输出
output = ''
while not output.endswith('Enter password:'): # 这里是shell提示输入密码的内容
resp = ssh.recv(5000)
output += resp.decode("utf-8")
print(output)
ssh.send(r'123456\\')
ssh.send('\n')
output = ''
while not output.endswith('# '):
resp = ssh.recv(5000)
output += resp.decode("utf-8")
print(output)
ssh.send('userdel -r msi')
ssh.send('\n')
ssh.send('userdel -r rog')
ssh.send('\n')
ssh.send('ls /home')
ssh.send('\n')
output = ''
while not output.endswith('# '):
resp = ssh.recv(5000)
output += resp.decode("utf-8")
print(output)
client.close()
print('{} done.'.format(ip))
if __name__ == "__main__":
with open("ips.txt", "r") as f:
data = [line.split() for line in f.readlines()]
server_list = [[i[0],i[6]] for i in data]
for server in server_list:
print('*******************{}'.format(server))
ssh_server(server)
print('*******************end')
output:
*******************['10.252.52.10', 'cn2icon001']
Last login: Wed Aug 10 05:55:04 2022 from 10.89.79.22
#################### Confidential Information #############################
# This server contains confidential information belonging to CN Systems #
# Inc. You cannot access this server unless you are a admin employee. #
# #
# THIS MESSAGE GENERATED BY (CN-Admin-Group-Policy) #
############################################################################
This Server is using Active Directory for Authentication
[icon@cn2icon001 ~]$ sudo su
Enter password:
[root@cn2icon001 icon]#
userdel -r msi
userdel: user 'msi' does not exist
[root@cn2icon001 icon]# userdel -r rog
userdel: user 'rog' does not exist
[root@cn2icon001 icon]# ls /home
cnadmin logstash hfadmin slim
[root@cn2icon001 icon]#
10.252.52.10 done.
*******************end