如果远程服务器未安装lsb-release
包,导致无法使用lsb_release -ds
命令获取系统发行版及版本信息,您可以采用以下替代方法来获取这些信息:
- 读取
/etc/os-release
文件:大多数现代Linux发行版会在/etc/os-release
文件中存储系统发行版和版本信息。您可以通过SSH连接到远程服务器并读取该文件的内容。
以下是修改后的Python脚本,不再使用lsb_release
命令,而是直接读取/etc/os-release
文件:
python
import nmap
import paramiko
def detect_remote_os(ip_address):
nm = nmap.PortScanner()
nm.scan(ip_address, arguments='-O')
try:
os_details = nm[ip_address]['osmatch'][0]
os_name = os_details['name']
os_accuracy = os_details['accuracy']
return os_name, os_accuracy
except KeyError:
return None, None
def is_linux_os(os_name):
return 'linux' in os_name.lower()
def get_remote_system_info(ip_address, username, password):
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(ip_address, username=username, password=password)
try:
# 获取系统发行版及版本信息
stdin, stdout, stderr = ssh.exec_command('cat /etc/os-release')
os_release_content = stdout.read().decode()
# 解析 /etc/os-release 文件内容
distro_info = {}
for line in os_release_content.split('\n'):
if '=' in line:
key, value = line.strip().split('=', 1)
distro_info[key] = value.strip('"').strip("'")
distro_name = distro_info.get('NAME', '')
distro_version = distro_info.get('VERSION', '')
# 获取系统架构信息
stdin, stdout, stderr = ssh.exec_command('uname -m')
arch = stdout.read().decode().strip()
return f"{distro_name} {distro_version}", arch
finally:
ssh.close()
if __name__ == '__main__':
target_ip = input("Enter the IP address of the remote server: ")
username = input("Enter the SSH username for the remote server: ")
password = input("Enter the SSH password for the remote server: ")
os_name, os_accuracy = detect_remote_os(target_ip)
if os_name is not None:
is_linux = is_linux_os(os_name)
if is_linux:
print(f"The remote server is running Linux (Accuracy: {os_accuracy}%)")
distro_version, arch = get_remote_system_info(target_ip, username, password)
print(f"Remote system distribution and version: {distro_version}")
print(f"Remote system architecture: {arch}")
else:
print(f"The remote server is NOT running Linux. Detected Operating System: {os_name} (Accuracy: {os_accuracy}%)")
else:
print("Failed to detect the operating system of the remote server.")
注意事项:
-
远程命令执行:确保您有足够的权限在远程服务器上执行
cat /etc/os-release
和uname -m
命令。如果远程服务器设置了严格的权限控制,可能需要使用具有相应权限的用户账户进行连接。 -
错误处理:虽然
/etc/os-release
文件在大多数现代Linux发行版中是标准的,但仍有少数发行版可能使用不同的文件格式或位置存储系统信息。在实际使用中,您可能需要添加更完善的错误捕获和处理机制,以应对文件不存在、无法读取或其他异常情况。