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

相关推荐
裕晟资质规划9 小时前
三类资质变更报告时限差在哪?军工 15 日、集成印制 10 日
大数据·服务器·网络
轻舟技术A9 小时前
Provider 不属于 Agent 核心:rpi 的分层理由与收益
服务器·网络
Escalating_xu10 小时前
【Linux 网络编程】TCP Socket 编程(上):从 listen、accept 到完整回显通信
linux·网络·tcp/ip
NetX行者10 小时前
Python 工程化入门:从脚本到规范的 Python 项目结构
网络·python
Yang961110 小时前
从相位噪声到实时带宽:HD-063B支撑的频谱实验项目
网络
happyprince10 小时前
01-整体观-DeepSeek-V4.1-Flash全貌解读
网络
是真的小外套10 小时前
2023年软考中级信息安全工程师|选择题考点+5道案例分析真题解析(含答案)
java·服务器·网络
一条泥憨鱼11 小时前
【计算机网络】| 从 MAC 到 NAT 的跨网段通信全链路
服务器·网络·学习·计算机网络·macos
Moyu_Friday11 小时前
网络安全基础-计算机网络应用与协议
网络协议·计算机网络
workflower12 小时前
超算中心聚焦高性能计算场景(HPC)
大数据·网络·人工智能·机器人·云计算·汽车