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服务且防火墙规则允许你从当前主机连接。

相关推荐
AI科技星12 小时前
数术工坊・八卷全书【本源创世终极版・万世定稿】
开发语言·网络·量子计算·拓扑学
AI科技星12 小时前
数术工坊・八卷全书(番外・实战升华副卷)【终极典藏定稿|完整无删减】
c语言·开发语言·网络·量子计算·agi
DreamLife☼12 小时前
OpenBCI-脑电信号的隐私与安全保护
网络·安全·开源硬件·脑机接口·eeg·openbci·神经科技
yyuuuzz12 小时前
云服务器软件部署的几个常见问题
运维·服务器·开发语言·网络·云计算·php·apache
dust_and_stars12 小时前
为什么ubuntu24 snap install code-server 不需要--classic?
网络·数据库
tiancaijiben12 小时前
阿里云日志服务SLS全流程对接与深度使用指南
网络·数据库
软件工程小施同学12 小时前
CCF A区块链论文分享-NDSS 2026(2)-CtPhishCapture:揭露针对加密货币钱包的基于凭证窃取的网络钓鱼诈骗(附pdf)
网络·pdf·区块链
aixingkong92113 小时前
NVIDIA CPU 特性演进解析
网络
学途路漫漫13 小时前
Ubuntu 24.04 国内网络环境全面优化指南
linux·网络·ubuntu
我是一颗柠檬13 小时前
【计算机网络全面教学】网络层与IP协议,子网划分到路由协议全掌握Day3(2026年)
网络协议·tcp/ip·计算机网络