有沒有辦法在ruby腳本中調用像last
這樣的命令?我可以使用%x
在腳本中調用諸如ls
和ls -l
之類的命令,但是對於由最後一個命令提供的複雜且不斷擴展的日誌信息,這可以接受嗎?在ruby腳本中調用命令
2
A
回答
2
下面是一個例子,來獲取用戶名,IP,啓動和持續時間:
%x(last -i).each_line do |line|
line.chomp! # Removes newline
break if line.empty? # last is done
# 3 possibilities to extract information :
user, *other_columns = line.split(' ') # 1. Use split
start = Time.parse(line[39,16]) # 2. Use known position of a column
ip = line[22,17].strip
if line =~/\((\d+):(\d+)\)/ # 3. Use a regex
duration = $1.to_i*60+$2.to_i
else
duration = nil
end
info={user: user, ip: ip, start: start, duration: duration}
#TODO: Check that user isn't "reboot"
puts info
end
# {:user=>"ricou", :ip=>"0.0.0.0", :start=>2016-11-01 21:29:00 +0100, :duration=>141}
# {:user=>"ricou", :ip=>"0.0.0.0", :start=>2016-11-01 15:21:00 +0100, :duration=>57}
哪些信息你需要什麼呢?
+0
IP地址。我想我可以用匹配來隔離他們,一旦我想出如何得到最後的工作。 – yukimoda
+0
我更新了代碼。您可能需要檢查列與我的寬度相同。 –
相關問題
- 1. 在ruby腳本中執行cd命令
- 2. 在Ruby腳本中運行命令行命令
- 3. 箭頭鍵在irb/ruby命令行腳本中不起作用?
- 4. 從Ruby腳本執行shell命令
- 5. 是「ruby腳本/插件」的命令嗎?
- 6. 批處理腳本 - 調用命令中旬腳本
- 7. php腳本調用gpg命令
- 8. 調用perl腳本作爲shell命令
- 9. SOAPUI Groovy腳本調用命令行
- 10. 從Groovy腳本調用psql命令
- 11. 從子腳本jython調用命令
- 12. Powershell調用命令腳本返回碼
- 13. 在bash腳本中使用find命令
- 14. 用PHP調用Ruby腳本
- 15. 在Ruby腳本中解析命令行參數
- 16. 如何在ruby腳本中運行maven build命令
- 17. Shebang命令從現有腳本調用腳本 - Python
- 18. 在另一個shell腳本中調用一個shell腳本(命令行工具)
- 19. 在Hudson調用的腳本中運行cp命令失敗
- 20. 從Ruby調用腳本php
- 21. 如何使用cron作業調用包含系統命令的ruby腳本?
- 22. 使用UNIX腳本/命令
- 23. su命令在shell腳本
- 24. 命令或腳本在Windows
- 25. 如何在期望腳本中使用bash腳本的命令?
- 26. 在Bash腳本中格式化用戶命令內的腳本
- 27. 如何運行具有Ruby腳本的.txt文件,而不使用命令行中的ruby命令
- 28. Subversion命令腳本
- 29. Shell腳本:在shell腳本中運行「exit」命令後執行命令
- 30. 從Ruby腳本中調用Elasticsearch Rest API
請參閱http://stackoverflow.com/questions/754494/reading-the-last-n-lines-of-a-file-in-ruby獲取ruby中的'last'命令。 – knut