1
我想要做的是通過SSH重複發出命令。如果我做這工作就好了以下內容:通過SSH會話關閉 - 這可能嗎?
(ns bla
(:require [clj-ssh.ssh :as ssh]))
(defn poll [func]
(while true
(func)
(Thread/sleep 1000)))
(defn exec-on-ssh
"Connects to a host and then does there whatever the passed command dictates"
[host command]
(let [agent (ssh/ssh-agent {})
session (ssh/session agent host {:strict-host-key-checking :no})]
(ssh/with-connection session
(poll (fn [] (let [result (ssh/ssh session {:cmd command})]
(println (get result :out))))))))
; usage:
(exec-on-ssh "some-host" "uptime | sed s/^.*average:\\ //")
但後來我不得不返回一個函數來代替,而我只是傳遞命令和處理功能的好主意:
(defn exec-on-ssh
"Connects to a host and then does there whatever the passed command dictates"
[host]
(let [agent (ssh/ssh-agent {})
session (ssh/session agent host {:strict-host-key-checking :no})]
(ssh/with-connection session
(fn [command process-fun]
(while true
(let [result (ssh/ssh session {:cmd command})]
(process-fun (get result :out))))))))
; usage:
((exec-on-ssh "some-host") "uptime | sed s/^.*average:\\ //" println)
但這會拋出以下異常:
JSchException Packet corrupt com.jcraft.jsch.Session.start_discard (Session.java:1050)
如果我正確地理解了這一點,它發生的原因是,當它執行任何操作時,會話已經消失。經過一番試驗,看起來像是因爲ssh/ssh
關閉而發生的。
有沒有辦法讓會話和具有第二種方法所提供的靈活性?
是的,這是我的愚蠢 - 我沒有返回我期望返回的函數。隨着改變你建議它的工作。 – dezso