写一个脚本,判断局域网内某个ip是否能访问,如果能访问,执行远程关机操作
时间: 2023-12-23 17:06:12 浏览: 77
以下是一个基于Python的脚本,可以用来判断局域网内某个IP地址是否能够访问,如果可以的话,则执行远程关机操作:
```python
import os
import platform
import subprocess
def ping(ip_address):
operating_system = platform.system().lower()
if "windows" in operating_system:
ping_reply = subprocess.run(["ping", "-n", "1", "-w", "500", ip_address], stdout=subprocess.PIPE).stdout.decode('utf-8')
if "Reply from" in ping_reply:
return True
elif "linux" in operating_system:
ping_reply = subprocess.run(["ping", "-c", "1", "-w", "500", ip_address], stdout=subprocess.PIPE).stdout.decode('utf-8')
if "1 received" in ping_reply:
return True
return False
def shutdown(ip_address):
operating_system = platform.system().lower()
if "windows" in operating_system:
os.system(f"shutdown /m \\\\{ip_address} /s /t 0")
elif "linux" in operating_system:
os.system(f"ssh {ip_address} sudo shutdown -h now")
if __name__ == "__main__":
ip_address = "192.168.0.100" # 修改为你需要检测的IP地址
if ping(ip_address):
shutdown(ip_address)
print(f"已向 {ip_address} 发送远程关机命令!")
else:
print(f"{ip_address} 无法访问!")
```
你需要将 `ip_address` 变量的值修改为你需要检测的IP地址,然后运行脚本即可。脚本会先对该IP地址进行 ping 测试,如果可以访问,则会执行相应的远程关机命令。如果无法访问,则会输出相应的提示信息。
阅读全文