因为实验室主机 ip 经常变换,但本地的ip相对稳定,所以编写一个小程序,运行在服务器上,每隔一段时间就发送它的ip给本地。这样不用每次都去实验室查看ip。
[2023 06 30] 后来,我发现用静态ip就解决问题了,这个方法属实鸡肋。
文章目录
核心代码
主要的代码来自于 [1]。函数 get_ip_address()
来自 [2],它还提供了用邮件的方法。crontab
则是参考 [3,4]。需要注意运行python需要指定python的位置 [5]。
client.py 运行在服务器上。每个一段时间就发送ip给本地。
'''[Update on April 7, 2023]
The main socket code is from [1].
The function get_ip_address() is from [2]. Ref [2] provides one way to use email.
The software `crontab` [3,4] can be used as one timing tool.
Pay attention that we should use `/bin/python3/` instead of `python` directly [5].
Email way is from [2,6]. Install Emain package [7,8].
Usage:
(1) Add your ip into the `info.json`. Note that don't move it to anywhere;
(2) Use the command "sudo service cron restart" to restart the service to make your changements actually be executed;
(3) Run the server.py to accept the ip.
Json format:
{"xxx": ["10.122.238.7", 8080]}
Use `crontab -e` to edit the crontab settings.
The `crontab` settings [4]:
*/10 * * * * /bin/python3 /home/ubuntu/Tools/client.py
Reasons: (1) We donot use `rsync` since we tend to use one easier way;
(2) We use `crontab` in case that the process is canceled accidentally.
Refs:
[1] https://blog.csdn.net/qq_30893653/article/details/128835816
[2] https://zhuanlan.zhihu.com/p/57754716
[3] https://wangsuo.blog.csdn.net/article/details/105168725
[4] https://blog.csdn.net/weixin_29767773/article/details/112838236
[5] https://blog.csdn.net/u014722022/article/details/124916365
[6] https://blog.csdn.net/xwh3165037789/article/details/124032813
[7] https://blog.csdn.net/qq_40833182/article/details/82504163
[8] https://blog.csdn.net/zhutianfu521/article/details/79040533
'''
import json
import socket
import time
import smtplib
import urllib.request
from email.mime.text import MIMEText
def dump_info(info):
'''Dump the information of user into 'info.json'
https://blog.csdn.net/flyingluohaipeng/article/details/127877058
'''
with open('info.json', 'w') as f:
json.dump(info, f)
def load_info():
with open('info.json', 'r') as f:
info = json.load(f)
return info
def get_hostname():
'''https://www.cnblogs.com/shaoyishi/p/17019442.html'''
hostname = socket.gethostname()
return hostname
def get_ip_address():
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.connect(("1.1.1.1", 80))
ipaddr=s.getsockname()[0]
s.close()
return ipaddr
def send_email(content):
smtp_server = "smtp.qq.com"
from_add = 'xxxxxx@qq.com' # from address
from_pwd = 'xxxxxx' # from passward
to_adds = ["xxxxxx@qq.com", ]
msg = MIMEText(content,'plain','utf-8')
msg['From'] = from_add
msg['To'] = to_adds[0]
msg['Subject'] = 'The IP address today'
try:
smtpObj = smtplib.SMTP(smtp_server)
smtpObj.login(from_add, from_pwd)
for to_add in to_adds:
smtpObj.sendmail(from_add, to_add, msg.as_string())
smtpObj.quit()
except smtplib.SMTPException as e:
print('error', e)
def send_once(users=None, content=''):
failed = [] # store the failed users
for user in users.keys():
try:
if users[user][0] != 'failed':
client = socket.socket()
client.connect(users[user]) # connect
client.send(content.encode("utf-8"))
client.close()
else:
#send_email(content=content)
pass
except Exception as e:
failed.append(user)
if client is not None:
client.close()
return failed
def main():
content = '{}: {}'.format(get_hostname(), get_ip_address())
users = load_info() # load all users
failed = []
for i in range(2):
failed = send_once(users=users, content=content)
time.sleep(3)
if len(failed) != 0:
for i in failed:
users[i][0] = 'failed'
else:
pass
dump_info(users)
main()
# One way to substitute the `crontab`
# while True:
# try:
# content = get_ip_address()
# send_once(content='3090-1: {}'.format(content))
# except:
# time.sleep(1)
# pass
server.py 运行在本地,如果需要接收ip了,便运行。
import socket
def get_ip_address():
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.connect(("1.1.1.1",80))
ipaddr=s.getsockname()[0]
s.close()
return ipaddr
ip = get_ip_address()
server = socket.socket()
server.bind(("{}".format(ip), 8080))
server.listen(5) # The max listening connections
print("Wait for connections..")
while True:
conn, addr =server.accept()
print("conn:", conn, "\naddr:", addr)
while True:
data =conn.recv(1024)
if not data:
print("Disconnect")
break
print("{}".format(data.decode("utf-8")))
server.close()
[1] python 网络编程socket 客户端给服务端发送消息_python socket发送消息_☆程序小黑★的博客-CSDN博客
[2] Ubuntu18.04 自动获取IP并邮件发送 - 知乎
[3] Ubuntu设置定时任务——每10秒钟执行一次命令(修改文件权限)_每10秒钟运行脚本_硕子鸽的博客-CSDN博客
[4] linux定时任务每小时_在Linux平台下每5、10或15分钟执行一次定时任务(Cron Job)…_伊红美兰的博客-CSDN博客
[5] shell中crontab执行shell调用python脚本未成功_crontab执行python脚本 不能正常完成_Johnny . Zuo的博客-CSDN博客