我在server1上,我编写了一个python脚本来执行另一个名为sendmail.py的python脚本,该脚本存在于服务器2上。
相同的代码如下:
import paramiko
import smtplib
import base64
ftpServer = "servname
ftpUser = "username"
ftpPwd = "*****"
port = 22
try:
client = paramiko.SSHClient()
client.load_system_host_keys()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
client.connect(ftpServer, port, ftpUser, ftpPwd)
print "Connection established with " + ftpServer
stdin, stdout, stderr = client.exec_command('python Codes/sendmail.py')
client.close()
except Exception, ex:
print "Error in sending e-mail: ", ex
另一方面,server2上的python代码sendmail.py(我试图在上面的脚本中执行)如下:
# Sending mail with an attachment file 'abc.txt'
# sendmail.py
import smtplib
import base64
filename = "abc.txt"
# Read a file and encode it into base64 format
fo = open(filename, "rb")
fo = open(filename, "rb")
filecontent = fo.read()
encodedcontent = base64.b64encode(filecontent) # base64
sender = 'xyz@gmail.com'
receiver = 'xyz@gmail.com'
marker = "AUNIQUEMARKER"
body ="""
This is a test email sent with an attachement.
"""
# Define the main headers.
part1 = """From: xyz@gmail.com
Subject: Trial mail
MIME-Version: 1.0
Content-Type: multipart/mixed; boundary=%s
--%s
""" % (marker, marker)
# Define the message action
part2 = """Content-Type: text/plain
Content-Transfer-Encoding:8bit
%s
--%s
""" % (body,marker)
# Define the attachment section
part3 = """Content-Type: multipart/mixed; name=\"%s\"
Content-Transfer-Encoding:base64
Content-Disposition: attachment; filename=%s
%s
--%s--
""" %(filename, filename, encodedcontent, marker)
message = part1 + part2 + part3
try:
smtpObj = smtplib.SMTP('localhost')
smtpObj.sendmail(sender, receiver, message)
print "Successfully sent email"
except Exception, ex:
print "Error: unable to send email", ex
独立地,代码sendmail.py(存在于server2上)运行正常。但问题是我无法通过server1上的paramiko从python代码执行相同的操作。没有错误,只是程序正常退出而没有邮件被发送。
尝试通过在不同位置打印来调试相同的内容 代码sendmail.py,我发现我在server1上运行的代码退出了 到达sendmail.py这一行:
fo = open(filename, "rb")
我不想将文件读取到当前服务器,而是应该从server2发送邮件,因为它独立发生。 请帮帮忙?
谢谢!