-1

我必须通过 ssh 编辑 root 拥有的文件。我在文件中添加一个条目,保留前 9 行并将其余行重新排序到一个临时文件中。我知道 > 覆盖了文件中的内容(这就是我想要的),但我需要将根目录保留为文件的所有者。我怎样才能做到这一点?谢谢!

#!/bin/bash
user=""
echo "User:"
read user
ssh xxxx@xxxx "
sed -i '\$a$user' file;
(head -n 9 file ; tail -n +10 file | sort) > temp;
cat temp > file;
rm -f temp
"
4

4 回答 4

1

不是cat换了主人,而是sed。当您使用sed -i时,它会执行以下操作:

mv file file.bak
sed '\$a$user' file.bak > file
rm file.bak

如您所见,这将使用原始文件的名称创建一个新文件,并且该文件归创建该文件的用户所有。

如果您想避免这种情况,请复制原始文件而不是使用该-i选项。

cp file /tmp/file.$$
sed '\$a$user' /tmp/file.$$ > file
rm /tmp/file.$$

或者您可以将sed其放入您的管道中:

sed '\$a$user' file | head -n 9 file ; tail -n +10 file | sort > temp
cat temp > file
rm temp
于 2013-08-01T18:03:55.517 回答
0
#!/bin/bash
user=""
echo "User:"
read user
ssh xxxx@xxxx "
sed -i '\$a$user' file;
(head -n 9 file ; tail -n +10 file | sort) > temp;
sudo mv temp file;
sudo chown root file
"

This will work better if on the xxxx machine the xxxx user you're logging in as has password-less access to sudo. You can do this by having this entry in your /etc/sudoers file there:

xxxx ALL=NOPASSWD: ALL
于 2013-08-01T18:08:49.793 回答
0

我认为登录的用户不能成为root?那么你最好的选择是使用 dd

dd if=tmpfile of=outfile

当然,在你的 tmp 文件上做所有的排序、seding、awking 和 greping。dd 在这种用法中是等效的 > 不创建新文件

于 2013-08-01T18:03:11.170 回答
0

自从我在 BASH 中写作以来已经有一段时间了,但我认为一个起点是

chown root $file // if you have a variable with the file name in 

或者

chown root thefile.txt //if you want it hard coded;

等式中的另一个变量是谁拥有应用程序猫的所有权?我认为无论谁是正在运行的应用程序的所有者,这就是决定其输出文件的所有权的方式

也许你也可以试试

$ sudo cat temp > file

因为会话将属于根,因此输出将属于根???

于 2013-08-01T18:02:20.143 回答