python 登录远程服务区,查询ip,判断是否存在某个ip

在Python中,登录远程服务器并查询IP地址通常涉及SSH(Secure Shell)连接和系统命令执行。这里使用paramiko库来实现这一功能。以下是一个基本的示例:

复制代码
import paramiko

# 定义远程服务器信息
hostname = 'your_remote_server_ip'
username = 'remote_username'
password = 'remote_password'

# 创建SSH客户端对象
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())

# 连接到远程服务器
try:
    ssh.connect(hostname, username=username, password=password)
except paramiko.AuthenticationException:
    print("Authentication failed.")
except Exception as e:
    print(f"Error connecting to the server: {e}")
else:
    # 在远程服务器上执行命令获取IP地址,这里假设是Linux环境
    stdin, stdout, stderr = ssh.exec_command('ip addr show')
    
    # 处理输出结果,找到公网或内网IP(这里以IPv4为例)
    for line in stdout.readlines():
        if 'inet' in line:
            ip_address = line.split()[1].split('/')[0]
            print(f"Found IP address: {ip_address}")

            # 判断这个IP是否存在,例如在一个预设列表中
            if ip_address in your_ip_list:
                print(f"The IP address {ip_address} exists in your list.")
            else:
                print(f"The IP address {ip_address} does not exist in your list.")

    # 关闭SSH连接
    ssh.close()

请将上述代码中的your_remote_server_ipremote_usernameremote_password替换为实际的远程服务器IP地址、用户名和密码。同时,your_ip_list应当替换为你预先定义好的IP列表。

注意:此代码片段仅用于演示如何通过SSH连接到远程服务器并执行命令获取IP地址,并对IP进行简单判断。根据实际操作系统类型(如Linux发行版、Windows等),可能需要调整获取IP地址的命令。此外,确保远程服务器已开启SSH服务且防火墙规则允许你从当前主机连接。

相关推荐
专注_每天进步一点点4 小时前
SLB(绑定弹性公网ip)-gateway-业务pod,gateway上出现reset by peer,业务pod上没有reset by peer
服务器·tcp/ip·gateway
CHANG_THE_WORLD5 小时前
TCP 三次握手彻底解析:SYN、ACK、SEQ、确认号与状态迁移
网络·网络协议·tcp/ip
2501_915106325 小时前
TraceEagle 代理抓包教程 本机和手机的 HTTPS 抓包方法
网络协议·计算机网络·网络安全·ios·adb·https·udp
小心我捶你啊6 小时前
数据采集和Web解锁不是一回事,从用途到规则区分
前端·爬虫·网络协议
DLYSB_6 小时前
基于 HTTP API 与 Modbus 协议的多源监控声光语音联动告警系统设计与实现
网络·网络协议·http·报警灯
Bobolink_7 小时前
手机端和电脑端的网络环境配置有什么不同?
网络·智能手机·电脑·网络环境
星恒讯工业路由器8 小时前
三大工业以太网协议选型对比
网络·物联网·ethercat·profinet·ethernet/ip·工业以太网协议
春卷同学8 小时前
HarmonyOS掌上记账APP开发实践第25篇:Image 组件高级用法 — 资源引用、网络图片与首字符占位方案
网络·华为·harmonyos
mounter6258 小时前
从内存隔离到运行时防线:透视 Linux 内核安全强化的博弈与演进
linux·网络·安全·linux kernel·kernel
Bug退散师11 小时前
多路IO复用[select版TCP服务器与poll版TCP服务器]与常用网络编程函数详解
linux·服务器·c语言·网络·驱动开发·tcp/ip