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_ip、remote_username、remote_password替换为实际的远程服务器IP地址、用户名和密码。同时,your_ip_list应当替换为你预先定义好的IP列表。

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

相关推荐
郝学胜-神的一滴7 小时前
Effective STL 条款09:慎重选择删除元素的方法
开发语言·网络·数据结构·c++·算法·stl
飞花漫卷,情随岁迁12 小时前
网络数据包转发与内核机制:小白概念科普
linux·运维·网络·数据库·mysql·oracle·智能路由器
laozhang70014 小时前
自己动手写一个 WebSocket 调试工具:告别广告与限制
网络·websocket·网络协议
LabVIEW开发15 小时前
5850E 质量流量计 + LabVIEW 流量怎么控?
服务器·网络·labview
国科安芯16 小时前
可信的电流:ASP4644S2B电源模块与星载电子供应链网络安全防护体系
网络·安全·web安全·架构·芯片·抗辐射
炸薯条!18 小时前
计算机网络基础知识(一):IP、域名、端口、网络模型与 HTTP 协议
网络
AndreaYYmm18 小时前
AF_PACKET 原始套接字抓包实战:手写一个 mini-tcpdump
c语言·网络协议
无奈笑天下18 小时前
银河麒麟高级服务器操作系统【通过 sysctl 调整内核网络参数】操作方法
运维·服务器·网络
LabVIEW开发18 小时前
GRAPHIX 真空计 + LabVIEW 真空度怎么读?
网络·labview