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

相关推荐
ysa0510302 小时前
【板子】Dinic(最大网络流)
网络
我星期八休息2 小时前
网络编程—应用层HTTP协议
linux·运维·开发语言·前端·网络·网络协议·http
ShineWinsu2 小时前
对于Linux:UDPsocket编程基础的解析
linux·运维·网络协议·udp·ip·端口号·进程间通信
ITxiaobing20233 小时前
IP库与AppsFlyer数据对账指南:破解国家/地区数据不一致的难题
网络·网络协议
有浔则灵3 小时前
GORM钩子函数详解
网络·安全·web安全
汇智信科5 小时前
图谱、向量、关键词、SQL多路一体,FastKG垂域召回率100%拉满
网络·数据库·ai编程·汇智信科·hsim·fastclaw·汇智龙虾
liulilittle5 小时前
论分布式系统的半开闭问题
服务器·网络·分布式·系统架构·竞态
FreeBuf_5 小时前
仅用六分钟,黑客借助Gemini CLI自主构建并迁移C&C僵尸网络
网络·人工智能
cyforkk5 小时前
Vercel 绑定自定义域名极简配置指南
服务器·前端·网络
Yang96116 小时前
探索无线新视界:鼎讯信通DXMP系列频谱仪模块深度剖析
运维·网络