Skip to content

Instantly share code, notes, and snippets.

@4513ECHO
Created February 19, 2024 12:06
Show Gist options
  • Save 4513ECHO/befc6fe69458bf7172b7cfc7d395a824 to your computer and use it in GitHub Desktop.
Save 4513ECHO/befc6fe69458bf7172b7cfc7d395a824 to your computer and use it in GitHub Desktop.
#!/usr/bin/env -S deno run --allow-read=.,/etc/ssh/sshd_config --allow-write=/etc/ssh/sshd_config
import { parseArgs } from "https://deno.land/std@0.216.0/cli/parse_args.ts";
import { TextLineStream } from "https://deno.land/std@0.216.0/streams/text_line_stream.ts";
import { ensure, is } from "https://deno.land/x/unknownutil@v3.16.3/mod.ts";
/* Usage:
* ./sshd_config.ts --config=<FILE> [--dry-run] [--sshd-config=<FILE>]
* --config=<FILE> Path to the JSON file containing the sshd_config options
* --dry-run Do not write to the sshd_config file (default: false)
* --sshd-config=<FILE> Path to the sshd_config file (default: /etc/ssh/sshd_config)
*/
const isOptions = is.ObjectOf({
_: is.ArrayOf(is.String),
"dry-run": is.OptionalOf(is.Boolean),
config: is.String,
"sshd-config": is.OptionalOf(is.String),
});
const options = ensure(parseArgs(Deno.args), isOptions);
const sshdConfigPath = options["sshd-config"] ?? "/etc/ssh/sshd_config";
const config = JSON.parse(await Deno.readTextFile(options.config));
const sshdConfigFile = await Deno.open(
sshdConfigPath,
{ read: true, write: !options["dry-run"] },
);
const { readable } = sshdConfigFile;
const { writable } = options["dry-run"] ? Deno.stdout : sshdConfigFile;
await readable
.pipeThrough(new TextDecoderStream())
.pipeThrough(new TextLineStream())
.pipeThrough(
new TransformStream<string, string>({
transform(chunk, controller) {
const optionName = chunk.split(/\s+/).at(0)?.replace(/^#/, "");
if (!optionName || !config[optionName]) {
return controller.enqueue(chunk + "\n");
}
const value = config[optionName] === true
? "yes"
: config[optionName] === false
? "no"
: config[optionName];
controller.enqueue(`${optionName} ${value}\n`);
},
}),
)
.pipeThrough(new TextEncoderStream())
.pipeTo(writable);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment