Skip to content

Commit b820b16

Browse files
committed
add ssh_cmd.py
1 parent 1f7bb07 commit b820b16

2 files changed

Lines changed: 184 additions & 0 deletions

File tree

README.md

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,3 +18,6 @@
1818

1919
* Python八大排序算法的实现:
2020
[*psf.py*](https://github.com/honglongwei/python-scripts/blob/master/psf.py)
21+
22+
* 远程执行命令、远程添加信任、远程自动分区挂盘:
23+
[*ssh_cmd.py*](https://github.com/honglongwei/python-scripts/blob/master/ssh_cmd.py)

ssh_cmd.py

Lines changed: 181 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,181 @@
1+
#! /usr/bin/env python
2+
# -*- coding: utf-8 -*-
3+
4+
import os
5+
import sys
6+
import time
7+
import argparse
8+
import datetime
9+
import paramiko
10+
11+
reload(sys)
12+
sys.setdefaultencoding("utf-8")
13+
14+
username = 'root'
15+
password = '123456'
16+
17+
rsa = [
18+
'ssh-rsa1',
19+
'ssh-rsa2'
20+
]
21+
22+
23+
#change return color
24+
def G(s):
25+
return "%s[32;2m%s%s[0m"%(chr(27), s, chr(27))
26+
def R(s):
27+
return "%s[31;2m%s%s[0m"%(chr(27), s, chr(27))
28+
29+
30+
def cmd_exc(ip, username, password):
31+
conn = paramiko.SSHClient()
32+
conn.set_missing_host_key_policy(paramiko.AutoAddPolicy())
33+
try:
34+
conn.connect(hostname = ip, username = username, password = password, timeout = 5)
35+
stdin, stdout, stderr = conn.exec_command(cmd)
36+
result = stdout.readlines()
37+
ret = ''.join(result)
38+
except:
39+
print R("无法连接")
40+
conn.close()
41+
try:
42+
return G(ret)
43+
except UnboundLocalError:
44+
pass
45+
46+
47+
def copy_rsa(ip, username, password):
48+
conn = paramiko.SSHClient()
49+
conn.set_missing_host_key_policy(paramiko.AutoAddPolicy())
50+
try:
51+
conn.connect(hostname = ip, username = username, password = password, timeout = 5)
52+
stdin, stdout, stderr = conn.exec_command("echo '{0}'>>/root/.ssh/authorized_keys;echo '{1}'>>/root/.ssh/authorized_keys".format(rsa[0], rsa[1]))
53+
result = stdout.readlines()
54+
ret = ''.join(result)
55+
except:
56+
print R("无法连接")
57+
conn.close()
58+
try:
59+
return G(ret)
60+
except UnboundLocalError:
61+
pass
62+
63+
64+
def auto_disk(Disk):
65+
if os.path.exists('./auto_disk.sh'):
66+
os.remove('./auto_disk.sh')
67+
with open('auto_disk.sh', 'a') as f:
68+
print >>f, '#!/bin/bash'
69+
print >>f, 'rpm -aq|grep expect'
70+
print >>f, 'if [ $? != 0 ];then'
71+
print >>f, ' yum install -y expect'
72+
print >>f, 'fi'
73+
print >>f, '/usr/bin/expect -c"'
74+
print >>f, 'set timeout -1'
75+
print >>f, 'spawn /sbin/fdisk /dev/{0}'.format(Disk)
76+
print >>f, 'expect \"*m for help*:\"'
77+
print >>f, 'send -- \"n\r\"'
78+
print >>f, 'expect \"*p*\n\"'
79+
print >>f, 'send -- \"p\r\"'
80+
print >>f, 'expect \"*number (1-4):\"'
81+
print >>f, 'send -- \"1\r\"'
82+
print >>f, 'expect \"*default 1*:\"'
83+
print >>f, 'send -- \"\r\"'
84+
print >>f, 'expect \"*default*:\"'
85+
print >>f, 'send -- \"\r\"'
86+
print >>f, 'expect \"*m for help*:\"'
87+
print >>f, 'send -- \"w\r\"'
88+
print >>f, 'expect eof'
89+
print >>f, '"'
90+
print >>f, 'mkfs.ext4 /dev/{0}1'.format(Disk)
91+
print >>f, 'echo "/dev/{0}1 /home/ ext4 defaults 0 0" >> /etc/fstab'.format(Disk)
92+
print >>f, 'mount /dev/{0}1 /home/'.format(Disk)
93+
94+
95+
def sftp_auto(ip, username, password):
96+
t = paramiko.Transport((ip,22))
97+
t.connect(username = username, password = password)
98+
sftp = paramiko.SFTPClient.from_transport(t)
99+
sftp.put('./auto_disk.sh','/tmp/auto_disk.sh')
100+
t.close()
101+
conn = paramiko.SSHClient()
102+
conn.set_missing_host_key_policy(paramiko.AutoAddPolicy())
103+
try:
104+
conn.connect(hostname = ip, username = username, password = password, timeout = 5)
105+
stdin, stdout, stderr = conn.exec_command('sh /tmp/auto_disk.sh')
106+
result = stdout.readlines()
107+
ret = ''.join(result)
108+
except:
109+
print R("无法连接")
110+
conn.close()
111+
try:
112+
return G(ret)
113+
except UnboundLocalError:
114+
pass
115+
116+
117+
118+
if __name__ == "__main__":
119+
parser=argparse.ArgumentParser(description='ssh_cmd', usage='%(prog)s [options]')
120+
parser.add_argument('-H','--host', nargs='?', dest='listhost', help='主机/多个主机用","分割')
121+
parser.add_argument('-f','--file', nargs='?', dest='filehost', help='主机列表文件')
122+
parser.add_argument('-m','--command', nargs='?', dest='command', help='执行命令')
123+
parser.add_argument('-I','--init', nargs='?', dest='init', help='自动分区挂盘')
124+
parser.add_argument('-A','--add', nargs='?', dest='add_rsa', help='添加信任')
125+
if len(sys.argv)==1:
126+
parser.print_help()
127+
else:
128+
args=parser.parse_args()
129+
cmd = args.command
130+
if args.listhost is not None and args.filehost is None:
131+
if args.command is not None:
132+
for ip in args.listhost.split(','):
133+
print G(ip)
134+
print G('-'*80)
135+
print cmd_exc(ip, username, password)
136+
print
137+
elif args.init is not None:
138+
auto_disk(args.init)
139+
for ip in args.listhost.split(','):
140+
print G(ip)
141+
print G('-'*80)
142+
print sftp_auto(ip, username, password)
143+
print
144+
elif args.add_rsa == 'root':
145+
for ip in args.listhost.split(','):
146+
print G(ip)
147+
print G('-'*80)
148+
print copy_rsa(ip, username, password)
149+
print
150+
else:
151+
print R('功能选项为空')
152+
elif args.listhost is None and args.filehost is not None:
153+
if args.command is not None:
154+
try:
155+
with open(args.filehost) as f:
156+
for ips in f.readlines():
157+
ip = ips.replace('\n', '')
158+
print G(ip)
159+
print G('-'*80)
160+
print cmd_exc(ip, username, password)
161+
print
162+
except IOError:
163+
print R('主机列表文件不存在')
164+
elif args.init is not None:
165+
auto_disk(args.init)
166+
for ip in args.listhost.split(','):
167+
print G(ip)
168+
print G('-'*80)
169+
print sftp_auto(ip, username, password)
170+
print
171+
elif args.add_rsa == 'root':
172+
for ip in args.listhost.split(','):
173+
print G(ip)
174+
print G('-'*80)
175+
print copy_rsa(ip, username, password)
176+
print
177+
else:
178+
print R('功能选项为空')
179+
else:
180+
print R('主机或命令不能为空')
181+

0 commit comments

Comments
 (0)