Zig
Zig
Start Concurrent SSH Commands with QuickCmdSend
See more SSH Examples
Demonstrates the Chilkat Ssh.QuickCmdSend method, which starts a remote command and immediately returns its channel number. The only argument is the command line. Internally it opens a session channel and sends an exec request.
Background: Because it returns without waiting, several commands can run concurrently over one authenticated connection — far faster than running them one after another when each has latency or slow work to do. Pair it with
QuickCmdCheck, which reports commands as they finish, so results can be collected in completion order rather than the order they were started.Chilkat Zig Downloads
const std = @import("std");
const chilkat = @import("chilkat");
pub fn main(init: std.process.Init) !void {
const alloc = init.arena.allocator();
// Demonstrates the Ssh.QuickCmdSend method, which starts a remote command and immediately
// returns its channel number. The only argument is the command line. Because it returns
// right away, several commands can run concurrently on the same SSH connection.
const ssh = try chilkat.Ssh.init();
defer ssh.deinit();
const ssh_port = 22;
ssh.connect("ssh.example.com", ssh_port) catch {
std.debug.print("{s}\n", .{try ssh.getLastErrorText(alloc)});
return;
};
// Normally you would not hard-code the password in source. You should instead obtain it
// from an interactive prompt, environment variable, or a secrets vault.
const password = "mySshPassword";
ssh.authenticatePw("mySshLogin", password) catch {
std.debug.print("{s}\n", .{try ssh.getLastErrorText(alloc)});
return;
};
// Start three commands without waiting for any of them to finish.
const channel1 = ssh.quickCmdSend("sleep 2; echo first done");
if (channel1 < 0) {
std.debug.print("{s}\n", .{try ssh.getLastErrorText(alloc)});
return;
}
const channel2 = ssh.quickCmdSend("echo second done");
if (channel2 < 0) {
std.debug.print("{s}\n", .{try ssh.getLastErrorText(alloc)});
return;
}
const channel3 = ssh.quickCmdSend("sleep 1; echo third done");
if (channel3 < 0) {
std.debug.print("{s}\n", .{try ssh.getLastErrorText(alloc)});
return;
}
std.debug.print("Started three concurrent commands.\n", .{});
// Use QuickCmdCheck to collect the results as each command completes.
ssh.disconnect();
}