使用示例(使用了默认用户root,和默认端口号22):
./mooon_ssh --h=192.168.4.1,192.168.4.2 -P=password -c='cat /etc/hosts'

#include "mooon/net/libssh2.h" // 提供远程执行命令接口
#include "mooon/sys/error.h"
#include "mooon/sys/stop_watch.h"
#include "mooon/utils/args_parser.h"
#include "mooon/utils/print_color.h"
#include "mooon/utils/string_utils.h"
#include "mooon/utils/tokener.h"
#include <iostream>// 被执行的命令,可为一条或多条命令,如:ls /&&whoami
STRING_ARG_DEFINE(c, "", "command to execute remotely");
// 逗号分隔的远程主机列表
STRING_ARG_DEFINE(h, "", "remote hosts");
// 远程主机的sshd端口号
INTEGER_ARG_DEFINE(uint16_t, p, 22, 10, 65535, "remote hosts port");
// 用户名
STRING_ARG_DEFINE(u, "root", "remote host user");
// 密码
STRING_ARG_DEFINE(P, "", "remote host password");// 连接超时,单位为秒
INTEGER_ARG_DEFINE(uint16_t, t, 10, 1, 65535, "timeout seconds to remote host");// 结果信息
struct ResultInfo
{bool success; // 为true表示执行成功std::string ip; // 远程host的IP地址uint32_t seconds; // 运行花费的时长,精确到秒ResultInfo(): success(false), seconds(0){}std::string str() const{std::string tag = success? "SUCCESS": "FAILURE";return mooon::utils::CStringUtils::format_string("[%s %s]: %u seconds", ip.c_str(), tag.c_str(), seconds);}
};inline std::ostream& operator <<(std::ostream& out, const struct ResultInfo& result)
{std::string tag = result.success? "SUCCESS": "FAILURE";out << "["PRINT_COLOR_YELLOW << result.ip << PRINT_COLOR_NONE" " << tag << "] " << result.seconds << " seconds";return out;
}// 使用示例:
// mooon_ssh -u=root -P=test -p=2016 -h="127.0.0.1,192.168.0.1" -c='ls /tmp&&ps aux|grep -c test'
int main(int argc, char* argv[])
{// 解析命令行参数std::string errmsg;if (!mooon::utils::parse_arguments(argc, argv, &errmsg)){fprintf(stderr, "parameter error: %s\n", errmsg.c_str());exit(1);}uint16_t port = mooon::argument::p->value();std::string commands = mooon::argument::c->value();std::string hosts = mooon::argument::h->value();std::string user = mooon::argument::u->value();std::string password = mooon::argument::P->value();mooon::utils::CStringUtils::trim(commands);mooon::utils::CStringUtils::trim(hosts);mooon::utils::CStringUtils::trim(user);mooon::utils::CStringUtils::trim(password);// 检查参数(-c)if (commands.empty()){fprintf(stderr, "parameter[-c]'s value not set\n");exit(1);}// 检查参数(-h)if (hosts.empty()){// 尝试从环境变量取值const char* hosts_ = getenv("HOSTS");if (NULL == hosts_){fprintf(stderr, "parameter[-h]'s value not set\n");exit(1);}hosts= hosts_;mooon::utils::CStringUtils::trim(hosts);if (hosts.empty()){fprintf(stderr, "parameter[-h]'s value not set\n");exit(1);}}// 检查参数(-u)if (user.empty()){fprintf(stderr, "parameter[-u]'s value not set\n");exit(1);}// 检查参数(-P)if (password.empty()){fprintf(stderr, "parameter[-P]'s value not set\n");exit(1);}std::vector<std::string> hosts_ip;const std::string& remote_hosts_ip = hosts;int num_remote_hosts_ip = mooon::utils::CTokener::split(&hosts_ip, remote_hosts_ip, ",", true);if (0 == num_remote_hosts_ip){fprintf(stderr, "parameter[-h] error\n");exit(1);}std::vector<struct ResultInfo> results(num_remote_hosts_ip);for (int i=0; i<num_remote_hosts_ip; ++i){bool color = true;int num_bytes = 0;int exitcode = 0;std::string exitsignal;std::string errmsg;const std::string& remote_host_ip = hosts_ip[i];results[i].ip = remote_host_ip;fprintf(stdout, "["PRINT_COLOR_YELLOW"%s"PRINT_COLOR_NONE"]\n", remote_host_ip.c_str());fprintf(stdout, PRINT_COLOR_GREEN);mooon::sys::CStopWatch stop_watch;try{mooon::net::CLibssh2 libssh2(remote_host_ip, port, user, password, mooon::argument::t->value());libssh2.remotely_execute(commands, std::cout, &exitcode, &exitsignal, &errmsg, &num_bytes);fprintf(stdout, PRINT_COLOR_NONE);color = false; // color = true;if ((0 == exitcode) && exitsignal.empty()){results[i].success = true;fprintf(stdout, "["PRINT_COLOR_YELLOW"%s"PRINT_COLOR_NONE"] SUCCESS\n", remote_host_ip.c_str());}else{results[i].success = false;if (exitcode != 0){fprintf(stderr, "%d: %s\n", exitcode, mooon::sys::Error::to_string(exitcode).c_str());}else if (!exitsignal.empty()){fprintf(stderr, "%s: %s\n", exitsignal.c_str(), errmsg.c_str());}}}catch (mooon::sys::CSyscallException& ex){if (color)fprintf(stdout, PRINT_COLOR_NONE); // color = true;fprintf(stderr, "["PRINT_COLOR_RED"%s"PRINT_COLOR_NONE"] failed: %s\n", remote_host_ip.c_str(), ex.str().c_str());}catch (mooon::utils::CException& ex){if (color)fprintf(stdout, PRINT_COLOR_NONE); // color = true;fprintf(stderr, "["PRINT_COLOR_RED"%s"PRINT_COLOR_NONE"] failed: %s\n", remote_host_ip.c_str(), ex.str().c_str());}results[i].seconds = stop_watch.get_elapsed_microseconds() / 1000000;std::cout << std::endl;} // for// 输出总结std::cout << std::endl;std::cout << "================================" << std::endl;int num_success = 0; // 成功的个数int num_failure = 0; // 失败的个数for (std::vector<struct ResultInfo>::size_type i=0; i<results.size(); ++i){const struct ResultInfo& result_info = results[i];std::cout << result_info << std::endl;if (result_info.success)++num_success;else++num_failure;}std::cout << "SUCCESS: " << num_success << ", FAILURE: " << num_failure << std::endl;return 0;
}

批量远程执行shell命令工具相关推荐

  1. java ganymed ssh2_java 远程执行Shell命令-通过ganymed-ssh2连接

    一.实现远程执行 此程序的目的是执行远程机器上的Shell脚本. [环境参数] 远程机器IP:192.168.243.21 用户名:user 密码:password 命令:python /data/a ...

  2. linux远程执行shell命令行,linux shell 远程执行命令--ftp

    linux shell 远程执行命令--ftp 2018-12-07 ftp有很多命令,熟悉这些命令你能大大的提高工作效率: FTP命令行格式为: ftp -v -d -i -n -g [主机名] , ...

  3. Python ssh 远程执行shell命令

    #工具 python paramiko #远程执行命令 import paramikossh = paramiko.SSHClient() key = paramiko.AutoAddPolicy() ...

  4. java使用ganymed-ssh2远程执行shell命令

    先上依赖 <!-- https://mvnrepository.com/artifact/ch.ethz.ganymed/ganymed-ssh2 --> <dependency&g ...

  5. python中command是什么意思_python中command执行shell命令脚本方法

    在Python中有一个模块commands也很容易做到以上的效果. 看一下三个函数: 1). commands.getstatusoutput(cmd) 用os.popen()执行命令cmd, 然后返 ...

  6. Ganymed-ssh2实现scp上传和下载文件,以及执行shell命令

    使用Ganymed-ssh2执行远程机器上的Shell脚本,还可以使用SCP来上传和下载文件 严禁转载!!! pom依赖 <dependency><groupId>com.ai ...

  7. jenkins 执行shell命令 command not found,make: *** [build] Error 127 解决办法

    本地执行shell命令成功,Jenkins 远程执行 shell命令有时 提示命令找不到,或者make的时候报错. 因为Jenkins执行shell时无法获取环境变量的原因导致 解决办法在shell脚 ...

  8. expect脚本同步文件,expect脚本指定host和要同步的文件,构建文件分发系统,批量远程执行命令...

    2019独角兽企业重金招聘Python工程师标准>>> expect脚本同步文件 更改权限 执行脚本 查看执行结果 expect eof需要加上,作用是等脚本命令执行完再进行退出 e ...

  9. android远程shell命令行,Android ADB使用之详细篇(五)执行Shell命令

    执行Shell命令 Adb提供了shell来在模拟器或手机上运行各种各样的命令,这些命令的二进制形式存在于这个路径中: /system/bin/...    无论是否进入adb远程shell,都可以使 ...

最新文章

  1. Extjs4 常用布局总结
  2. 职场升职加薪不二法则,德到领袖偷偷告诉你
  3. 3大常见光伏加盟骗局大起底
  4. python自动化接口测试中的cookies怎么实现_python接口自动化测试--requests cookies处理...
  5. Count Color poj2777 线段树
  6. Ajax(5)UpdatePanel的使用方法
  7. Jenkins file一行代码部署.NET程序到K8S
  8. core控制器属性注入的用处_理解 ASP.NET Core 依赖注入
  9. 软件测试面试常见问题
  10. 解密!区块链BaaS是什么?
  11. S7-200与配备CU240BE-2的G120变频器进行USS通信的具体方法和步骤
  12. 【今日CV 计算机视觉论文速览 第99期】Fri, 12 Apr 2019
  13. 写给新人的话——谈谈应届生入职后应该怎样快速成长
  14. Gartner 魔力象限:安全信息和事件管理 2020
  15. 广东开放大学形考任务财务会计(二)(专,2022秋)形成性考核3答案
  16. DayDayUp:计算机技术与软件专业技术资格证书之《系统集成项目管理工程师》证书考试历年真题及其解析之2017年/2018年
  17. linux下安装grads
  18. Sequencer: Deep LSTM for Image Classification(LSTM在CV领域杀出一条血路,完美超越Swin与ConvNeXt等前沿算法)
  19. WINDOWS10 启动失败 你的电脑/设备需要修复
  20. 2021-11-09 - Redis - GUI Tool - RDM - 学习/实践

热门文章

  1. banner轮播图切换插件
  2. 国家基础地理信息中心编制完成新版世界地图
  3. android 悬浮窗权限申请
  4. abb机器人示教器io信号关联_ABB机器人IO基本操作接线步骤
  5. 华为OD机试题(AB卷)真题抽中记录文档(更新到 6 月 21 日)
  6. MT2007-快速判断一个数能否被整除
  7. IOS唤起H5微信或支付宝收银台
  8. 8051的特殊功能寄存器
  9. 0x80004005,远程桌面发生身份验证错误
  10. HTML5期末大作业:家乡网站设计——石家庄(10页) HTML+CSS+JavaScrip 旅游网页html 家乡介绍html网页设计 dw旅游景点网页设计 web课程设计网页规划与设计...