coding=utf-8
import paramiko
import time
from email.mime.text import MIMEText
from email.mime.base import MIMEBase
from email.mime.multipart import MIMEMultipart
from email.header import Header
from email import encoders
from email.utils import parseaddr,formataddr
import smtplib
def send_mail(str):
def _format_addr(s):
name,addr=parseaddr(s)
return formataddr((\
Header(name,'utf-8').encode(),\
addr))
from_addr= 'lei@uagserver.com'
print ('%s' %from_addr)
#password=raw_input('Password: ')
password='123456789'
print('%s' %password)
#smtp_server=raw_input('SMTP server: ')
smtp_server='10.121.215.5'
print('%s' %smtp_server)
#to_addr=raw_input('To: ')
to_addr='lei@uagserver.com'
print('%s' %to_addr)
msg = MIMEMultipart()
#msg.attach(MIMEText('hello,I\'m your son','plain','utf8'))
msg.attach(MIMEText(str,'plain','utf8'))
msg['From'] = _format_addr(u'Python爱好者 <%s>' %from_addr )
msg['To'] = _format_addr(u'管理员 <%s>' % to_addr)
msg['Subject'] = Header(u'来自SMTP的问候……', 'utf-8').encode()
with open('D:\\git_repo\\temp.txt','r') as f:
mime=MIMEBase('text','pain',filename='temp.txt')
mime.add_header('Content-Disposition', 'attachment', filename='temp.txt')
mime.add_header('Content-ID', '<0>')
mime.add_header('X-Attachment-Id', '0')
mime.set_payload(f.read())
encoders.encode_base64(mime)
msg.attach(mime)
server=smtplib.SMTP(smtp_server,25)
server.set_debuglevel(1)
server.login(from_addr,password)
server.sendmail(from_addr,[to_addr],msg.as_string())
server.quit()
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(“10.101.200.233”,22,“user”, “password”)
channel = ssh.invoke_shell()
try:
channel.send(“su\n”)
while not channel.recv_ready():
print (“Working…”)
time.sleep(2)
print (channel.recv(1024))
channel.send("%s\n" % “password”)
while not channel.recv_ready():
print (“Authenticating…”)
time.sleep(2)
print (channel.recv(1024))
command=[“uptime\n”,“cat /proc/meminfo\n”,“cat /proc/cpuinfo\n”]
print (command)
for cmd in command:
print (cmd)
time.sleep(10)
channel.send(cmd)
while not channel.recv_ready():
print(“Working on part 3…”)
time.sleep(10)
#context1=channel.recv(1024)
data=channel.recv(9999)
print (data)
print (type(data))
with open('temp.txt','a') as f:
f.write(data.decode(encoding='utf-8'))
with open('temp.txt','r') as f1:
context1=f1.read()
send_mail(context1)
#print context1
except Exception as e:
print (e)
ssh.close()