使用示例(使用了默认用户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. Linux远程执行Shell命令或脚本

    ## 远程执行shell命令 ssh [user]@[server] '[command]' # eg. ssh root@192.168.1.1 'uptime' ## 远程执行本地shell脚本 ...

  2. Linux远程执行shell命令

    Linux远程执行shell命令   在Linux系统中,我们经常想在A机器上,执行B机器上的SHELL命令. 下面这种方案,是一种流行可靠的方案. 1.SSH无密码登录 # 本地服务器执行(A机器) ...

  3. Java远程执行Shell命令

    1. Jar包:ganymed-ssh2-build210.jar 2. 步骤: a) 连接: Connection conn = new Connection(ipAddr); conn.conne ...

  4. Python ssh 远程执行shell命令

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

  5. Java SSH远程执行Shell命令、shell脚本实现(Ganymed SSH)

    jar包下载地址: http://www.ganymed.ethz.ch/ssh2/ 此源码的好处就是没有依赖很多其他的包,拷贝过来干干净净.具体代码实现可以看下文,或参考官方文档,在下载的压缩包里g ...

  6. 使用JSch远程执行shell命令

    package com.nihaorz.jsch; import com.jcraft.jsch.Channel; import com.jcraft.jsch.ChannelExec; import ...

  7. 第3节 sqoop:7、通过java代码远程连接linux执行shell命令

    数据库的数据同步软件sqoop 数据同步 关系型数据库到大数据平台 任务:sqoop 是批量导入数据太慢,如何做到实时的数据同步 实时的数据同步工具: canal 阿里开源的一个数据库数据实时同步的软 ...

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

    自动同步文件 #!/usr/bin/expect set " spawn rsync -av root@.txt /tmp/ expect { "yes/no" { se ...

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

    7月20日任务 20.31 expect脚本同步文件20.32 expect脚本指定host和要同步的文件20.33 构建文件分发系统20.34 批量远程执行命令扩展:shell多线程 http:// ...

随机推荐

  1. ubuntu 安装u盘恢复

    XP下进入CMD命令窗体,Vista及7/8下右键以管理员方式运行DOS窗体(win8.1:开始屏幕-windows系统-命令提示符) 输入DISKPART,会显示计算机名,及DISKPART> ...

  2. MYsql系统函数和联合查询

    函数是SQL里的关键字,用于对字段里的数据进行操作.函数是一个命令,通常与字段名称或者是表达式联合使用,处理输入的数据并产生结果 常用函数 控制函数 字符串函数 数学函数 日期时间函数 汇总函数 CA ...

  3. time和datetime

    一.time模块常用函数1. time()函数time()函数返回的是时间戳(timestamp).所谓时间戳指的是从1970年1月1日00:00:00开始按秒计算的偏移量.其他返回时间戳方式的函数还 ...

  4. hive 显示分区

    显示某一张表的分区值 show partitions table_name;

  5. EasyUI 修改

    <script type="text/javascript"> <!-- js --> /*=============================修改对 ...

  6. Ubuntu Server17.10配置静态IP

    今天心血来潮,装个虚拟机Ubuntu打算学点东西,遇到了一些问题,同时借助百度的力量解决了,下面是配置的过程. 一. 安装virtualbox 不知道从哪个版本开始,安装虚拟盒子的时候没有了安装虚拟网 ...

  7. Hibernate分页查询的两个方法

    Hibernate中HQL查询语句有一个分页查询, session.setMaxResult(参数)和session.setFirstResult(参数) 如果只设置session.setMaxRes ...

  8. centos 系统下查看时间时区以及修改

    1.系统时间查看及修改: Centos 6 查看系统时间:# date

  9. 如何搭建hibernate框架

    我写这篇博客,主要是想让大家能够快速上手hibernate,本人建议学习框架,应该一个框架一个框架学习,别一上手就三大框架整合,学习之类的.这里只是单独搭建hibernate框架,让大家 能够更好的上 ...

  10. Mysql优化性能优化21条

    今天,数据库的操作越来越成为整个应用的性能瓶颈了,这点对于Web应用尤其明显.关于数据库的性能,这并不只是DBA才需要担心的事,而这更是我们程序员需要去关注的事情.当我们去设计数据库表结构,对操作数据 ...