以其他用户身份运行ant

Bre*_*zen 3 ant

如果我以root身份运行任务,是否有办法检测其作为root运行并以不同用户身份运行某些任务.

我有一些需要以root身份运行的任务,但其他需要以当前用户身份运行的任务.

pru*_*nge 5

如果当前用户具有某个名称(例如"root"),则可以使用以下内容仅运行某些目标.

<condition property="rootTasksEnabled">
    <equals arg1="${user.name}" arg2="root" />
</condition>

<target name="do-stuff-if-root" if="rootTasksEnabled">
    <echo>Doing root stuff</echo>
</target>
Run Code Online (Sandbox Code Playgroud)

至于以不同的用户身份运行Ant,您可以使用带有su命令的<exec>来生成另一个Ant进程:

<target name="do-stuff" depends="do-stuff-if-root, do-other-stuff" />

<condition property="rootTasksEnabled">
    <equals arg1="${user.name}" arg2="root" />
</condition>
<property name="targetToRunAsOtherUser" value="do-stuff-as-other-user" />
<property name="otherUser" value="johnny" />

<target name="do-stuff-if-root" if="rootTasksEnabled">
    <echo>Doing root stuff</echo>

    <exec executable="su">
        <arg value="-c" />
        <arg value="${ant.home}/bin/ant -buildfile ${ant.file} ${targetToRunAsOtherUser}" />
        <arg value="${otherUser}" />
    </exec>
</target>

<target name="do-other-stuff">
    <echo>Doing normal build stuff</echo>
</target>

<target name="do-stuff-as-other-user">
    <echo>I am running as ${user.name}</echo>
    <echo>My home is ${user.home}</echo>
</target>
Run Code Online (Sandbox Code Playgroud)

此示例仅适用于Unix.要在Windows中执行此操作,您可以使用runas命令而不是su.