From 4a0c66bcc0364244bae80ee5617eabe4bec8f7ac Mon Sep 17 00:00:00 2001 From: whyour Date: Fri, 14 Apr 2023 21:04:57 +0800 Subject: [PATCH] =?UTF-8?q?=E4=BF=AE=E5=A4=8D=E5=88=9D=E5=A7=8B=E5=8C=96?= =?UTF-8?q?=20ssh=20=E9=85=8D=E7=BD=AE=E6=96=87=E4=BB=B6=E4=B8=8D=E5=AD=98?= =?UTF-8?q?=E5=9C=A8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- back/services/sshKey.ts | 30 ++++++++++++++++++++---------- 1 file changed, 20 insertions(+), 10 deletions(-) diff --git a/back/services/sshKey.ts b/back/services/sshKey.ts index 03df8723..ec717dae 100644 --- a/back/services/sshKey.ts +++ b/back/services/sshKey.ts @@ -15,13 +15,22 @@ export default class SshKeyService { private sshConfigHeader = `Include ${path.join(this.sshPath, '*.config')}`; constructor(@Inject('logger') private logger: winston.Logger) { - this.initSshConfigFile() + this.initSshConfigFile(); } private initSshConfigFile() { - const config = fs.readFileSync(this.sshConfigFilePath, { encoding: 'utf-8' }) + let config = ''; + if (existsSync(this.sshConfigFilePath)) { + config = fs.readFileSync(this.sshConfigFilePath, { encoding: 'utf-8' }); + } else { + fs.writeFileSync(this.sshConfigFilePath, ''); + } if (!config.includes(this.sshConfigHeader)) { - fs.writeFileSync(this.sshConfigFilePath, `${this.sshConfigHeader}\n\n${config}`, { encoding: 'utf-8' }); + fs.writeFileSync( + this.sshConfigFilePath, + `${this.sshConfigHeader}\n\n${config}`, + { encoding: 'utf-8' }, + ); } } @@ -47,17 +56,18 @@ export default class SshKeyService { } } - private generateSingleSshConfig( - alias: string, - host: string, - proxy?: string, - ) { + private generateSingleSshConfig(alias: string, host: string, proxy?: string) { if (host === 'github.com') { host = `ssh.github.com\n Port 443\n HostkeyAlgorithms +ssh-rsa\n PubkeyAcceptedAlgorithms +ssh-rsa`; } const proxyStr = proxy ? ` ProxyCommand nc -v -x ${proxy} %h %p\n` : ''; - const config = `Host ${alias}\n Hostname ${host}\n IdentityFile ${path.join(this.sshPath, alias)}\n StrictHostKeyChecking no\n${proxyStr}`; - fs.writeFileSync(`${path.join(this.sshPath, `${alias}.config`)}`, config, { encoding: 'utf8' }); + const config = `Host ${alias}\n Hostname ${host}\n IdentityFile ${path.join( + this.sshPath, + alias, + )}\n StrictHostKeyChecking no\n${proxyStr}`; + fs.writeFileSync(`${path.join(this.sshPath, `${alias}.config`)}`, config, { + encoding: 'utf8', + }); } private removeSshConfig(alias: string) {