|
| 1 | +#!/usr/bin/python |
| 2 | +# -*- coding: utf-8 -*- |
| 3 | +""" |
| 4 | +Created by PyCharm. |
| 5 | +File Name: LinuxBashShellScriptForOps:allow-access-port-on-remote-host.py |
| 6 | +Version: 0.0.1 |
| 7 | +Author: dgden |
| 8 | +Author Email: dgdenterprise@gmail.com |
| 9 | +URL: https://github.com/DingGuodong/LinuxBashShellScriptForOps |
| 10 | +Download URL: https://github.com/DingGuodong/LinuxBashShellScriptForOps/tarball/master |
| 11 | +Create Date: 2021/3/18 |
| 12 | +Create Time: 21:17 |
| 13 | +Description: allow the public ip address of this host access a port of the remote host |
| 14 | +Long Description: |
| 15 | +
|
| 16 | + design thought: |
| 17 | + 1. get public ip address of this host |
| 18 | + 2. construct the cmd: remove old rule, add new rule |
| 19 | + 3. execute the command on remote host via SSH protocol |
| 20 | +
|
| 21 | +References: projects/others/aliyun/ECS/SecurityGroup/add-Internet-IP-to-aliyun-ecs-security-group.py |
| 22 | +Prerequisites: pip install requests |
| 23 | + pip install paramiko |
| 24 | +Development Status: 3 - Alpha, 5 - Production/Stable |
| 25 | +Environment: Console |
| 26 | +Intended Audience: System Administrators, Developers, End Users/Desktop |
| 27 | +License: Freeware, Freely Distributable |
| 28 | +Natural Language: English, Chinese (Simplified) |
| 29 | +Operating System: POSIX :: Linux, Microsoft :: Windows |
| 30 | +Programming Language: Python :: 2.6 |
| 31 | +Programming Language: Python :: 2.7 |
| 32 | +Topic: Utilities |
| 33 | + """ |
| 34 | + |
| 35 | +import requests |
| 36 | + |
| 37 | +IP_QUERY_API_S1 = "https://ifconfig.co/ip" |
| 38 | +IP_QUERY_API_S2 = "https://api.ip.sb/ip" |
| 39 | + |
| 40 | + |
| 41 | +def get_public_ip_from_api(api): |
| 42 | + query_ip_api_url = api |
| 43 | + |
| 44 | + headers = { |
| 45 | + 'Cache-Control': "no-cache", |
| 46 | + } |
| 47 | + |
| 48 | + data = "" |
| 49 | + try: |
| 50 | + # Pass a (connect, read) timeout tuple, or a single float to set both timeouts to the same value |
| 51 | + response = requests.request("GET", query_ip_api_url, headers=headers, timeout=(10, 5)) |
| 52 | + if response.ok: |
| 53 | + data = response.text.strip() |
| 54 | + except Exception as _: |
| 55 | + del _ |
| 56 | + |
| 57 | + return data |
| 58 | + |
| 59 | + |
| 60 | +def get_public_ip(): |
| 61 | + ip1, ip2 = map(get_public_ip_from_api, (IP_QUERY_API_S1, IP_QUERY_API_S2)) |
| 62 | + return ip1 if ip1 != "" else ip2 |
| 63 | + |
| 64 | + |
| 65 | +def execute_commands_on_remote_host(host, command, **kwargs): |
| 66 | + import paramiko |
| 67 | + |
| 68 | + port = kwargs.get("port") or 22 |
| 69 | + username = kwargs.get("username") or 'root' |
| 70 | + key_filename = kwargs.get("key_filename") # os.path.expanduser(r'~/.ssh/id_rsa') |
| 71 | + timeout = kwargs.get("timeout") or 5 |
| 72 | + |
| 73 | + client = paramiko.SSHClient() |
| 74 | + client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) |
| 75 | + client.connect(hostname=host, port=port, username=username, key_filename=key_filename, timeout=timeout) |
| 76 | + |
| 77 | + stdin, stdout, stderr = client.exec_command(command=command, |
| 78 | + get_pty=True) # type: paramiko.ChannelStdinFile, list, paramiko.ChannelStderrFile |
| 79 | + """ |
| 80 | + warning:: |
| 81 | + The server may reject this request depending on its ``AcceptEnv`` |
| 82 | + setting; such rejections will fail silently (which is common client |
| 83 | + practice for this particular request type). Make sure you |
| 84 | + understand your server's configuration before using! |
| 85 | + """ |
| 86 | + for line in stdout: |
| 87 | + print "Stdout: ", line, |
| 88 | + |
| 89 | + for line in stdout: |
| 90 | + print "Stderr: ", line, |
| 91 | + client.close() |
| 92 | + |
| 93 | + |
| 94 | +if __name__ == '__main__': |
| 95 | + internet_ip = get_public_ip() |
| 96 | + |
| 97 | + # Tips: `| awk '$1=$1'` 或 `| awk 'NF--'` 去除字符串两端的(多个)空格, |
| 98 | + # Decrementing NF causes the values of fields past the new value to be lost, |
| 99 | + # and the value of $0 to be recomputed, with the fields being separated by the value of OFS. |
| 100 | + |
| 101 | + command_remove_old_rule = '''firewall-cmd --permanent --zone=public ''' \ |
| 102 | + '''--remove-rich-rule="$(firewall-cmd --list-all | awk '/fw_temp_kw/','$1=$1')"; ''' \ |
| 103 | + '''firewall-cmd --reload''' |
| 104 | + |
| 105 | + # use `log prefix="fw_temp_kw" level="info"` as comment in firewall-cmd |
| 106 | + # refer: https://serverfault.com/questions/893112/migrating-from-iptables-to-firewalld-commenting-rules |
| 107 | + command_add_new_rule = 'firewall-cmd --permanent ' \ |
| 108 | + '--add-rich-rule="rule family="ipv4" source address="{ip}" ' \ |
| 109 | + 'port protocol="tcp" port="50009" log prefix="fw_temp_kw" level="info" accept";' \ |
| 110 | + 'firewall-cmd --reload'.format(ip=internet_ip) |
| 111 | + the_command = ';'.join((command_remove_old_rule, command_add_new_rule)) |
| 112 | + # print the_command |
| 113 | + |
| 114 | + execute_commands_on_remote_host("47.240.129.250", the_command, |
| 115 | + port=22, |
| 116 | + username='root', |
| 117 | + key_filename=r"C:\Users\dgden\.ssh\exportedkey201310171355" |
| 118 | + ) |
0 commit comments