一开始我认为rust划分mod很简单。我是这样做的。新建一个pack.rs里面写代码
use ssh2::Session;
pub mod pack{
pub struct Config {
pub ip: String,
pub port: i32,
pub username: String,
pub password: String,
}
pub struct SSH {
pub session: Session,
pub config: Config,
}
impl SSH {
pub fn new(ip: &str, username: &str, password: &str, port: i32) -> Self {
if port < 0 || port > 65535 {
panic!("port{}不合法", port)
}
let mut ip = ip.to_string();
let username = username.to_string();
let password = password.to_string();
if !ip.contains(".") {
ip = format!("192.168.101.{}", ip)
}
let config = Config { ip, port, username, password };
let session = Self::connect(&config).unwrap();
Self { session, config }
}
fn connect(c: &Config) -> Result<Session, anyhow::Error> {
println!("建立对{}:{}的ssh连接", c.ip, c.port);
let tcp = TcpStream::connect(format!("{}:{}", c.ip, c.port)).unwrap();
let mut sess = Session::new().unwrap();
sess.set_tcp_stream(tcp);
sess.handshake()?;
sess.userauth_password(c.username.as_str(), c.password.as_str())?;
println!("连接成功");
Ok(sess)
}
pub fn exec_wait(&self, cmd: &str) {
println!("执行命令: {}", cmd);
let mut channel = self.session.channel_session().unwrap();
channel.exec(cmd).unwrap();
let mut s = String::new();
channel.read_to_string(&mut s).unwrap();
println!("{}", s);
channel.wait_close();
println!("响应码:{}", channel.exit_status().unwrap());
}
pub fn exec_long(&self, cmd: &str) {
println!("执行长时间命令: {}", cmd);
let mut channel = self.session.channel_session().unwrap();
channel.exec(cmd).unwrap();
let mut reader = BufReader::new(&mut channel);
loop{
let mut line = String::new();
if let Ok(s) = reader.read_line(&mut line){
if s>0{
print!("{}",line);
}else{
break
}
}else{
break
}
}
channel.wait_close();
println!("响应码:{}", channel.exit_status().unwrap());
}
}
}
然后在lib.js中引入
pub mod pack;
最后在main.rs中使用
use my_project::pack;
fn main(){
let _ = pack::SSH::new("180", "root", "", 22);
}
类似这样,可是无论如何都pack找不到SSH,很奇怪。
我的goland一直提示不出来。rust插件很难用。 很郁闷。最终居然是vscode里的插件发现了问题,提示应该用 pack::pack::SSH 才行。很奇怪,最后发现原来是建立了pack.rs之后不用再写一层 pub mod pack
了。写了就又嵌套了一层,所以应该去掉就好了.
除此之外还有一个坑是use必须在mod里面写,不能在开头写,否则找不到use的模块。