溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

Ruby腳本在Linux中管理網(wǎng)絡(luò)端口

發(fā)布時(shí)間:2024-09-15 10:44:39 來源:億速云 閱讀:81 作者:小樊 欄目:建站服務(wù)器

在Linux中,你可以使用Ruby腳本來管理網(wǎng)絡(luò)端口

  1. 安裝Ruby(如果尚未安裝):
sudo apt-get update
sudo apt-get install ruby
  1. 創(chuàng)建一個(gè)名為port_manager.rb的Ruby腳本文件:
touch port_manager.rb
  1. 編輯port_manager.rb文件并添加以下內(nèi)容:
require 'socket'

def open_port?(ip, port)
  begin
    socket = TCPSocket.new(ip, port)
    socket.close
    true
  rescue Errno::ECONNREFUSED, Errno::EHOSTUNREACH
    false
  end
end

def manage_port(action, ip, port)
  case action
  when "check"
    if open_port?(ip, port)
      puts "Port #{port} is open on #{ip}"
    else
      puts "Port #{port} is closed on #{ip}"
    end
  when "open"
    # To open a port, you need to run a server on that port.
    # Here's an example of how to do it with a simple HTTP server:
    server = TCPServer.new(ip, port)
    puts "Port #{port} is now open on #{ip}"
    Thread.new do
      loop do
        client = server.accept
        client.puts "Hello from port #{port}!"
        client.close
      end
    end
  when "close"
    # Closing a port requires stopping the service running on that port.
    # This is beyond the scope of a simple script and depends on the service itself.
    puts "To close a port, you need to stop the service running on it."
  else
    puts "Invalid action. Use 'check', 'open', or 'close'."
  end
end

if ARGV.length == 3
  action, ip, port = ARGV
  manage_port(action, ip, port.to_i)
else
  puts "Usage: ruby port_manager.rb<action> <ip> <port>"
  puts "Actions: check, open, close"
end
  1. 運(yùn)行腳本以檢查、打開或關(guān)閉端口。例如,要檢查IP地址為192.168.1.100的設(shè)備上的端口8080是否開放,請運(yùn)行:
ruby port_manager.rb check 192.168.1.100 8080

請注意,此腳本僅用于演示目的。在實(shí)際應(yīng)用中,你可能需要根據(jù)你的需求對其進(jìn)行修改和優(yōu)化。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI