2021/9/10

system service : report ip to another server

啟動後,等 remote server up,然後把 自己的 ip 送過去..
先把自己的 public key 送過去 (user charles-chang)。設定好 ssh 免 password.
準備 service file:
xeontitan:/etc/systemd/system# cat reportip.service 
[Unit]
Description=send my ip address file to rdsuper
Afteter=network-online.target

[Service]
User=charles-chang
WorkingDirectory=/home/charles-chang
ExecStart=/home/charles-chang/reportip.sh

[Install]
WantedBy=multi-user.target
charles-chang 自己的 shell script:
cat /home/charles-chang/reportip.sh 
#!/bin/bash
while true
do
	ping -c 1 rdsuper
	if [ $? -eq 0 ]
	then
		break
	fi
	sleep 10
done
ip addr > $HOSTNAME-ip
scp $HOSTNAME-ip rdsuper:~/
enable & start
systemctl daemon-reload
systemctl enable reportip.service
systemctl start reportip.service



改用 python 做,用 socket 直接 update /etc/hosts 的話: 叫 chatgpt 寫...
為了測試,先改 /etc/hosts_u 系統測試 OK 再改 /etc/hosts..

~$ cat updatehosts.py
import socket

def update_hosts_file(ip, hostname):
    # Read the current contents of /etc/hosts
    with open('/etc/hosts_u', 'r') as file:
        lines = file.readlines()

    # Check if the hostname already exists in the file
    exists = False
    for i, line in enumerate(lines):
        if hostname in line:
            # Update the existing entry
            lines[i] = f"{ip} {hostname}\n"
            exists = True
            break

    # If the hostname does not exist, add a new entry
    if not exists:
        lines.append(f"{ip} {hostname}\n")

    # Write the updated contents back to /etc/hosts
    with open('/etc/hosts_u', 'w') as file:
        file.writelines(lines)

def start_server(port):
    server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    server_socket.bind(('0.0.0.0', port))
    server_socket.listen(5)
    print(f"Listening on port {port}...")

    while True:
        client_socket, client_address = server_socket.accept()
        print(f"Connection from {client_address}")

        data = client_socket.recv(1024).decode('utf-8')
        if data:
            ip, hostname = data.split(',')
            update_hosts_file(ip, hostname)
            print(f"Updated /etc/hosts with IP: {ip}, Hostname: {hostname}")

        client_socket.close()

if __name__ == "__main__":
    start_server(61234)
然後 systemd service file:
$ cat updatehosts.service
[Unit]
Description=Sender Python Service
After=network-online.target
Wants=network-online.target

[Service]
Type=simple
ExecStart=/usr/bin/python3 /home/charles-chang/updatehosts.py
Restart=on-failure

[Install]
WantedBy=multi-user.target

至於 sender 端,因為要等 dhcp ready...
要注意 nic interface name 是不是 eno1,不一定是。
要依照自己的系統修改。

$ cat sender_updatehosts.py
import socket
import time
import netifaces

SERVER_IP = '192.168.147.182' 
SERVER_PORT = 61234            

def get_ip_address(interface):
    try:
        ip_address = netifaces.ifaddresses(interface)[netifaces.AF_INET][0]['addr']
    except (ValueError, KeyError):
        ip_address = None
    hostname = socket.gethostname()
    return ip_address, hostname

def send_data(ip, hostname):
    with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
        s.connect((SERVER_IP, SERVER_PORT))
        message = f"{ip},{hostname}"
        s.sendall(message.encode('utf-8'))
        response = s.recv(1024)
        print('Received', repr(response))

def main():
    interface = 'eno1'
    
    while True:
        ip, hostname = get_ip_address(interface)
        if ip:
            break
        print("Waiting for valid IP address...")
        time.sleep(5)

    send_data(ip, hostname)

if __name__ == "__main__":
    main()

沒有留言:

張貼留言